blob: eda6bc45aa8f742a72c503b7b3e359d2d28d0a78 [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;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050092import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani67df64b2012-12-14 12:09:36 -080093import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080094import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070095import com.android.internal.util.Preconditions;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000096import com.android.server.LocalServices;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -070097import com.android.server.ServiceThread;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -060098import com.android.server.SystemService;
99
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700100import com.google.android.collect.Lists;
101import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700102
Oscar Montemayora8529f62009-11-18 10:14:20 -0800103import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700104import java.io.FileDescriptor;
105import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800106import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700107import java.security.MessageDigest;
108import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700109import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700110import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800111import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700112import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700113import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700114import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700115import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800116import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700117import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800118import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800119import java.util.Map.Entry;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700120import java.util.Objects;
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700121import java.util.Set;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700122import java.util.UUID;
Svet Ganovf6d424f12016-09-20 20:18:53 -0700123import java.util.concurrent.CopyOnWriteArrayList;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700124import java.util.concurrent.atomic.AtomicInteger;
125import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700126
Fred Quintana60307342009-03-24 22:48:12 -0700127/**
128 * A system service that provides account, password, and authtoken management for all
129 * accounts on the device. Some of these calls are implemented with the help of the corresponding
130 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
131 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700132 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700133 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700134 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700135public class AccountManagerService
136 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800137 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700138 private static final String TAG = "AccountManagerService";
139
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600140 public static class Lifecycle extends SystemService {
141 private AccountManagerService mService;
142
143 public Lifecycle(Context context) {
144 super(context);
145 }
146
147 @Override
148 public void onStart() {
Fyodor Kupolovda993802016-09-21 14:47:10 -0700149 mService = new AccountManagerService(new Injector(getContext()));
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600150 publishBinderService(Context.ACCOUNT_SERVICE, mService);
151 }
152
153 @Override
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600154 public void onUnlockUser(int userHandle) {
155 mService.onUnlockUser(userHandle);
156 }
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700157
158 @Override
159 public void onCleanupUser(int userHandle) {
160 mService.onCleanupUser(userHandle);
161 }
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600162 }
163
Svet Ganov5d09c992016-09-07 09:57:41 -0700164 final Context mContext;
Fred Quintana60307342009-03-24 22:48:12 -0700165
Fred Quintana56285a62010-12-02 14:20:51 -0800166 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700167 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700168 private UserManager mUserManager;
Fyodor Kupolovda993802016-09-21 14:47:10 -0700169 private final Injector mInjector;
Fred Quintana56285a62010-12-02 14:20:51 -0800170
Svet Ganov5d09c992016-09-07 09:57:41 -0700171 final MessageHandler mHandler;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700172
Fred Quintana60307342009-03-24 22:48:12 -0700173 // Messages that can be sent on mHandler
174 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700175 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700176
Fred Quintana56285a62010-12-02 14:20:51 -0800177 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700178 private static final String PRE_N_DATABASE_NAME = "accounts.db";
Fred Quintana7be59642009-08-24 18:29:25 -0700179 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800180
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800181 private static final int SIGNATURE_CHECK_MISMATCH = 0;
182 private static final int SIGNATURE_CHECK_MATCH = 1;
183 private static final int SIGNATURE_CHECK_UID_MATCH = 2;
184
Carlos Valdivia91979be2015-05-22 14:11:35 -0700185 static {
186 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Christopher Tatebded68f2017-02-21 11:41:55 -0800187 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
188 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700189 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700190
191 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700192 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
193
Amith Yamasani04e0d262012-02-14 11:50:53 -0800194 static class UserAccounts {
195 private final int userId;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700196 final AccountsDb accountsDb;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800197 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
198 credentialsPermissionNotificationIds =
199 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
200 private final HashMap<Account, Integer> signinRequiredNotificationIds =
201 new HashMap<Account, Integer>();
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);
431
432 final int callingUid = Binder.getCallingUid();
433 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");
438 int userId = UserHandle.getCallingUserId();
439 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
440 String msg = String.format("uid %s cannot explicitly add accounts of type: %s",
441 callingUid, account.type);
442 throw new SecurityException(msg);
443 }
444 /*
445 * Child users are not allowed to add accounts. Only the accounts that are shared by the
446 * parent profile can be added to child profile.
447 *
448 * TODO: Only allow accounts that were shared to be added by a limited user.
449 */
450 // fails if the account already exists
451 long identityToken = clearCallingIdentity();
452 try {
453 UserAccounts accounts = getUserAccounts(userId);
454 return addAccountInternal(accounts, account, password, extras, callingUid,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800455 (Map<String, Integer>) packageToVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800456 } finally {
457 restoreCallingIdentity(identityToken);
458 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700459 }
460
461 @Override
Dmitry Dementyev52745472016-12-02 10:27:45 -0800462 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
463 String accountType) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800464 int callingUid = Binder.getCallingUid();
465 boolean isSystemUid = UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
466 List<String> managedTypes =
467 getTypesForCaller(callingUid, UserHandle.getUserId(callingUid), isSystemUid);
468
469 if ((accountType != null && !managedTypes.contains(accountType))
470 || (accountType == null && !isSystemUid)) {
471 throw new SecurityException(
472 "getAccountsAndVisibilityForPackage() called from unauthorized uid "
473 + callingUid + " with packageName=" + packageName);
474 }
475 if (accountType != null) {
476 managedTypes = new ArrayList<String>();
477 managedTypes.add(accountType);
478 }
479
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800480 long identityToken = clearCallingIdentity();
481 try {
482 return getAccountsAndVisibilityForPackage(packageName, managedTypes, callingUid,
483 getUserAccounts(UserHandle.getUserId(callingUid)));
484 } 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) {
494 int uid = 0;
495 try {
496 uid = mPackageManager.getPackageUidAsUser(packageName,
497 UserHandle.getUserId(callingUid));
498 } catch (NameNotFoundException e) {
499 Log.d(TAG, "Package not found " + e.getMessage());
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800500 return new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800501 }
502
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800503 Map<Account, Integer> result = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800504 for (String accountType : accountTypes) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700505 synchronized (accounts.dbLock) {
506 synchronized (accounts.cacheLock) {
507 final Account[] accountsOfType = accounts.accountCache.get(accountType);
508 if (accountsOfType != null) {
509 for (Account account : accountsOfType) {
510 result.put(account,
511 resolveAccountVisibility(account, packageName, accounts));
512 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800513 }
514 }
515 }
516 }
517 return filterSharedAccounts(accounts, result, callingUid, packageName);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800518 }
519
520 @Override
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800521 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700522 Preconditions.checkNotNull(account, "account cannot be null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700523 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800524 int userId = UserHandle.getUserId(callingUid);
525 UserAccounts accounts = getUserAccounts(userId);
526 if (!isAccountManagedByCaller(account.type, callingUid, userId)
527 && !isSystemUid(callingUid)) {
528 String msg =
529 String.format("uid %s cannot get secrets for account %s", callingUid, account);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700530 throw new SecurityException(msg);
531 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700532 synchronized (accounts.dbLock) {
533 synchronized (accounts.cacheLock) {
534 return getPackagesAndVisibilityForAccountLocked(account, accounts);
535 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700536 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800537 }
538
539 /**
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700540 * Returns Map with all package names and visibility values for given account.
541 * The method and returned map must be guarded by accounts.cacheLock
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800542 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800543 * @param account Account to get visibility values.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800544 * @param accounts UserAccount that currently hosts the account and application
545 *
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700546 * @return Map with cache for package names to visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800547 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700548 private @NonNull Map<String, Integer> getPackagesAndVisibilityForAccountLocked(Account account,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800549 UserAccounts accounts) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700550 Map<String, Integer> accountVisibility = accounts.visibilityCache.get(account);
551 if (accountVisibility == null) {
552 Log.d(TAG, "Visibility was not initialized");
553 accountVisibility = new HashMap<>();
554 accounts.visibilityCache.put(account, accountVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800555 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700556 return accountVisibility;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700557 }
558
559 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700560 public int getAccountVisibility(Account account, String packageName) {
561 Preconditions.checkNotNull(account, "account cannot be null");
562 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800563 int callingUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700564 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
565 if (!isAccountManagedByCaller(account.type, callingUid, accounts.userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800566 && !isSystemUid(callingUid)) {
567 String msg = String.format(
568 "uid %s cannot get secrets for accounts of type: %s",
569 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700570 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800571 throw new SecurityException(msg);
572 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700573 return resolveAccountVisibility(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800574 }
575
576 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800577 * Method returns visibility for given account and package name.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800578 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800579 * @param account The account to check visibility.
580 * @param packageName Package name to check visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800581 * @param accounts UserAccount that currently hosts the account and application
582 *
583 * @return Visibility value, AccountManager.VISIBILITY_UNDEFINED if no value was stored.
584 *
585 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700586 private int getAccountVisibilityFromCache(Account account, String packageName,
587 UserAccounts accounts) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700588 synchronized (accounts.cacheLock) {
589 Map<String, Integer> accountVisibility =
590 getPackagesAndVisibilityForAccountLocked(account, accounts);
591 Integer visibility = accountVisibility.get(packageName);
592 return visibility != null ? visibility : AccountManager.VISIBILITY_UNDEFINED;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800593 }
594 }
595
596 /**
597 * Method which handles default values for Account visibility.
598 *
599 * @param account The account to check visibility.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800600 * @param packageName Package name to check visibility
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800601 * @param accounts UserAccount that currently hosts the account and application
602 *
603 * @return Visibility value, the method never returns AccountManager.VISIBILITY_UNDEFINED
604 *
605 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800606 private Integer resolveAccountVisibility(Account account, @NonNull String packageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800607 UserAccounts accounts) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800608 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800609 int uid = -1;
610 try {
611 long identityToken = clearCallingIdentity();
612 try {
613 uid = mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
614 } finally {
615 restoreCallingIdentity(identityToken);
616 }
617 } catch (NameNotFoundException e) {
618 Log.d(TAG, "Package not found " + e.getMessage());
619 return AccountManager.VISIBILITY_NOT_VISIBLE;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800620 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800621
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800622 // System visibility can not be restricted.
623 if (UserHandle.isSameApp(uid, Process.SYSTEM_UID)) {
624 return AccountManager.VISIBILITY_VISIBLE;
625 }
626
627 int signatureCheckResult =
628 checkPackageSignature(account.type, uid, accounts.userId);
629
630 // Authenticator can not restrict visibility to itself.
631 if (signatureCheckResult == SIGNATURE_CHECK_UID_MATCH) {
632 return AccountManager.VISIBILITY_VISIBLE; // Authenticator can always see the account
633 }
634
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800635 if (isSpecialPackageKey(packageName)) {
636 Log.d(TAG, "Package name is forbidden: " + packageName);
637 return AccountManager.VISIBILITY_NOT_VISIBLE;
638 }
639
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800640 // Return stored value if it was set.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700641 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800642
643 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
644 return visibility;
645 }
646
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800647 boolean isPrivileged = isPermittedForPackage(packageName, accounts.userId,
648 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
649
650 // Device/Profile owner gets visibility by default.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800651 if (isProfileOwner(uid)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800652 return AccountManager.VISIBILITY_VISIBLE;
653 }
654 // Apps with READ_CONTACTS permission get visibility by default even post O.
655 boolean canReadContacts = checkReadContactsPermission(packageName, accounts.userId);
656
657 boolean preO = isPreOApplication(packageName);
658 if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
659 || (preO && checkGetAccountsPermission(packageName, accounts.userId))
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800660 || canReadContacts || isPrivileged) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800661 // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
662 // match.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700663 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800664 AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800665 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
666 visibility = AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
667 }
668 } else {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700669 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800670 AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800671 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
672 visibility = AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
673 }
674 }
675 return visibility;
676 }
677
678 /**
679 * Checks targetSdk for a package;
680 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800681 * @param packageName Package name
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800682 *
683 * @return True if package's target SDK is below {@link android.os.Build.VERSION_CODES#O}, or
684 * undefined
685 */
686 private boolean isPreOApplication(String packageName) {
687 try {
688 long identityToken = clearCallingIdentity();
689 ApplicationInfo applicationInfo;
690 try {
691 applicationInfo = mPackageManager.getApplicationInfo(packageName, 0);
692 } finally {
693 restoreCallingIdentity(identityToken);
694 }
695
696 if (applicationInfo != null) {
697 int version = applicationInfo.targetSdkVersion;
698 return version < android.os.Build.VERSION_CODES.O;
699 }
700 return true;
701 } catch (NameNotFoundException e) {
702 Log.d(TAG, "Package not found " + e.getMessage());
703 return true;
704 }
Dmitry Dementyev58fa83622016-12-20 18:08:51 -0800705 }
706
707 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700708 public boolean setAccountVisibility(Account account, String packageName, int newVisibility) {
709 Preconditions.checkNotNull(account, "account cannot be null");
710 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800711 int callingUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700712 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
713 if (!isAccountManagedByCaller(account.type, callingUid, accounts.userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800714 && !isSystemUid(callingUid)) {
715 String msg = String.format(
716 "uid %s cannot get secrets for accounts of type: %s",
717 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700718 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800719 throw new SecurityException(msg);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700720 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700721 return setAccountVisibility(account, packageName, newVisibility, true /* notify */,
722 accounts);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700723 }
724
725 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800726 * Updates visibility for given account name and package.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700727 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800728 * @param account Account to update visibility.
729 * @param packageName Package name for which visibility is updated.
730 * @param newVisibility New visibility calue
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800731 * @param notify if the flag is set applications will get notification about visibility change
732 * @param accounts UserAccount that currently hosts the account and application
733 *
734 * @return True if account visibility was changed.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700735 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800736 private boolean setAccountVisibility(Account account, String packageName, int newVisibility,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800737 boolean notify, UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700738 synchronized (accounts.dbLock) {
739 synchronized (accounts.cacheLock) {
740 Map<String, Integer> packagesToVisibility;
741 if (notify) {
742 if (isSpecialPackageKey(packageName)) {
743 packagesToVisibility =
744 getRequestingPackages(account, accounts);
745 } else {
746 if (!packageExistsForUser(packageName, accounts.userId)) {
747 return false; // package is not installed.
748 }
749 packagesToVisibility = new HashMap<>();
750 packagesToVisibility.put(packageName,
751 resolveAccountVisibility(account, packageName, accounts));
752 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800753 } else {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700754 // Notifications will not be send.
755 if (!isSpecialPackageKey(packageName) &&
756 !packageExistsForUser(packageName, accounts.userId)) {
757 // package is not installed and not meta value.
758 return false;
Nicolas Prevotf7d8df12016-09-16 17:45:34 +0100759 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700760 packagesToVisibility = new HashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800761 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700762
763 if (!updateAccountVisibilityLocked(account, packageName, newVisibility, accounts)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800764 return false;
765 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800766
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700767 if (notify) {
768 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
769 .entrySet()) {
770 if (packageToVisibility.getValue()
771 != AccountManager.VISIBILITY_NOT_VISIBLE) {
772 notifyPackage(packageToVisibility.getKey(), accounts);
773 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700774 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700775 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700776 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700777 return true;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800778 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700779 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700780 }
781
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700782 // Update account visibility in cache and database.
783 private boolean updateAccountVisibilityLocked(Account account, String packageName,
784 int newVisibility, UserAccounts accounts) {
785 final long accountId = accounts.accountsDb.findDeAccountId(account);
786 if (accountId < 0) {
787 return false;
788 }
789
790 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
791 try {
792 if (!accounts.accountsDb.setAccountVisibility(accountId, packageName,
793 newVisibility)) {
794 return false;
795 }
796 } finally {
797 StrictMode.setThreadPolicy(oldPolicy);
798 }
799 Map<String, Integer> accountVisibility =
800 getPackagesAndVisibilityForAccountLocked(account, accounts);
801 accountVisibility.put(packageName, newVisibility);
802 return true;
803 }
804
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700805 @Override
806 public void registerAccountListener(String[] accountTypes, String opPackageName) {
807 int callingUid = Binder.getCallingUid();
808 mAppOpsManager.checkPackage(callingUid, opPackageName);
809 registerAccountListener(accountTypes, opPackageName,
810 getUserAccounts(UserHandle.getUserId(callingUid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800811 }
812
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700813 private void registerAccountListener(String[] accountTypes, String opPackageName,
814 UserAccounts accounts) {
815 synchronized (accounts.mReceiversForType) {
816 if (accountTypes == null) {
817 // null for any type
818 accountTypes = new String[] {null};
819 }
820 for (String type : accountTypes) {
821 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
822 if (receivers == null) {
823 receivers = new HashMap<>();
824 accounts.mReceiversForType.put(type, receivers);
825 }
826 Integer cnt = receivers.get(opPackageName);
827 receivers.put(opPackageName, cnt != null ? cnt + 1 : 1);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800828 }
829 }
830 }
831
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700832 @Override
833 public void unregisterAccountListener(String[] accountTypes, String opPackageName) {
834 int callingUid = Binder.getCallingUid();
835 mAppOpsManager.checkPackage(callingUid, opPackageName);
836 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
837 synchronized (accounts.mReceiversForType) {
838 if (accountTypes == null) {
839 // null for any type
840 accountTypes = new String[] {null};
841 }
842 for (String type : accountTypes) {
843 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
844 if (receivers == null || receivers.get(opPackageName) == null) {
845 throw new IllegalArgumentException("attempt to unregister wrong receiver");
846 }
847 Integer cnt = receivers.get(opPackageName);
848 if (cnt == 1) {
849 receivers.remove(opPackageName);
850 } else {
851 receivers.put(opPackageName, cnt - 1);
852 }
853 }
854 }
855 }
856
857 // Send notification to all packages which can potentially see the account
858 private void sendNotificationAccountUpdated(Account account, UserAccounts accounts) {
859 Map<String, Integer> packagesToVisibility = getRequestingPackages(account, accounts);
860 // packages with VISIBILITY_USER_MANAGED_NOT_VISIBL still get notification.
861 // Should we notify VISIBILITY_NOT_VISIBLE packages when account is added?
862 for (Entry<String, Integer> packageToVisibility : packagesToVisibility.entrySet()) {
863 if (packageToVisibility.getValue() != AccountManager.VISIBILITY_NOT_VISIBLE) {
864 notifyPackage(packageToVisibility.getKey(), accounts);
865 }
866 }
867 }
868
869 /**
870 * Sends a direct intent to a package, notifying it of account visibility change.
871 *
872 * @param packageName to send Account to
873 * @param accounts UserAccount that currently hosts the account
874 */
875 private void notifyPackage(String packageName, UserAccounts accounts) {
876 Intent intent = new Intent(AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED);
877 intent.setPackage(packageName);
878 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
879 mContext.sendBroadcastAsUser(intent, new UserHandle(accounts.userId));
880 }
881
882 // Returns a map from package name to visibility, for packages subscribed
883 // to notifications about any account type, or type of provided account
884 // account type or all types.
885 private Map<String, Integer> getRequestingPackages(Account account, UserAccounts accounts) {
886 Set<String> packages = new HashSet<>();
887 synchronized (accounts.mReceiversForType) {
888 for (String type : new String[] {account.type, null}) {
889 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
890 if (receivers != null) {
891 packages.addAll(receivers.keySet());
892 }
893 }
894 }
895 Map<String, Integer> result = new HashMap<>();
896 for (String packageName : packages) {
897 result.put(packageName, resolveAccountVisibility(account, packageName, accounts));
898 }
899 return result;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800900 }
901
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800902 private boolean packageExistsForUser(String packageName, int userId) {
903 try {
904 long identityToken = clearCallingIdentity();
905 try {
906 mPackageManager.getPackageUidAsUser(packageName, userId);
907 return true; // package exist
908 } finally {
909 restoreCallingIdentity(identityToken);
910 }
911 } catch (NameNotFoundException e) {
912 return false;
913 }
914 }
915
916 /**
917 * Returns true if packageName is one of special values.
918 */
919 private boolean isSpecialPackageKey(String packageName) {
920 return (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)
921 || AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName));
922 }
923
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800924 private void sendAccountsChangedBroadcast(int userId) {
925 Log.i(TAG, "the accounts changed, sending broadcast of "
926 + ACCOUNTS_CHANGED_INTENT.getAction());
927 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700928 }
929
930 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -0700931 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
932 throws RemoteException {
933 try {
934 return super.onTransact(code, data, reply, flags);
935 } catch (RuntimeException e) {
936 // The account manager only throws security exceptions, so let's
937 // log all others.
938 if (!(e instanceof SecurityException)) {
939 Slog.wtf(TAG, "Account Manager Crash", e);
940 }
941 throw e;
942 }
943 }
944
Amith Yamasani258848d2012-08-10 17:06:33 -0700945 private UserManager getUserManager() {
946 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700947 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700948 }
949 return mUserManager;
950 }
951
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700952 /**
953 * Validate internal set of accounts against installed authenticators for
954 * given user. Clears cached authenticators before validating.
955 */
956 public void validateAccounts(int userId) {
957 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700958 // Invalidate user-specific cache to make sure we catch any
959 // removed authenticators.
960 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
961 }
962
963 /**
964 * Validate internal set of accounts against installed authenticators for
965 * given user. Clear cached authenticators before validating when requested.
966 */
967 private void validateAccountsInternal(
968 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700969 if (Log.isLoggable(TAG, Log.DEBUG)) {
970 Log.d(TAG, "validateAccountsInternal " + accounts.userId
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700971 + " isCeDatabaseAttached=" + accounts.accountsDb.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600972 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700973 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700974
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700975 if (invalidateAuthenticatorCache) {
976 mAuthenticatorCache.invalidateCache(accounts.userId);
977 }
978
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700979 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
980 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700981 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700982
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700983 synchronized (accounts.dbLock) {
984 synchronized (accounts.cacheLock) {
985 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800986
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700987 // Get a map of stored authenticator types to UID
988 final AccountsDb accountsDb = accounts.accountsDb;
989 Map<String, Integer> metaAuthUid = accountsDb.findMetaAuthUid();
990 // Create a list of authenticator type whose previous uid no longer exists
991 HashSet<String> obsoleteAuthType = Sets.newHashSet();
992 SparseBooleanArray knownUids = null;
993 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
994 String type = authToUidEntry.getKey();
995 int uid = authToUidEntry.getValue();
996 Integer knownUid = knownAuth.get(type);
997 if (knownUid != null && uid == knownUid) {
998 // Remove it from the knownAuth list if it's unchanged.
999 knownAuth.remove(type);
1000 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001001 /*
1002 * The authenticator is presently not cached and should only be triggered
1003 * when we think an authenticator has been removed (or is being updated).
1004 * But we still want to check if any data with the associated uid is
1005 * around. This is an (imperfect) signal that the package may be updating.
1006 *
1007 * A side effect of this is that an authenticator sharing a uid with
1008 * multiple apps won't get its credentials wiped as long as some app with
1009 * that uid is still on the device. But I suspect that this is a rare case.
1010 * And it isn't clear to me how an attacker could really exploit that
1011 * feature.
1012 *
1013 * The upshot is that we don't have to worry about accounts getting
1014 * uninstalled while the authenticator's package is being updated.
1015 *
1016 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001017 if (knownUids == null) {
1018 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
1019 }
1020 if (!knownUids.get(uid)) {
1021 // The authenticator is not presently available to the cache. And the
1022 // package no longer has a data directory (so we surmise it isn't
1023 // updating). So purge its data from the account databases.
1024 obsoleteAuthType.add(type);
1025 // And delete it from the TABLE_META
1026 accountsDb.deleteMetaByAuthTypeAndUid(type, uid);
1027 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001028 }
1029 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001030
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001031 // Add the newly registered authenticator to TABLE_META. If old authenticators have
1032 // been re-enabled (after being updated for example), then we just overwrite the old
1033 // values.
1034 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1035 accountsDb.insertOrReplaceMetaAuthTypeAndUid(entry.getKey(), entry.getValue());
1036 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001037
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001038 final Map<Long, Account> accountsMap = accountsDb.findAllDeAccounts();
1039 try {
1040 accounts.accountCache.clear();
1041 final HashMap<String, ArrayList<String>> accountNamesByType
1042 = new LinkedHashMap<>();
1043 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1044 final long accountId = accountEntry.getKey();
1045 final Account account = accountEntry.getValue();
1046 if (obsoleteAuthType.contains(account.type)) {
1047 Slog.w(TAG, "deleting account " + account.name + " because type "
1048 + account.type
1049 + "'s registered authenticator no longer exist.");
1050 Map<String, Integer> packagesToVisibility =
1051 getRequestingPackages(account, accounts);
1052 accountsDb.beginTransaction();
1053 try {
1054 accountsDb.deleteDeAccount(accountId);
1055 // Also delete from CE table if user is unlocked; if user is
1056 // currently locked the account will be removed later by
1057 // syncDeCeAccountsLocked
1058 if (userUnlocked) {
1059 accountsDb.deleteCeAccount(accountId);
1060 }
1061 accountsDb.setTransactionSuccessful();
1062 } finally {
1063 accountsDb.endTransaction();
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001064 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001065 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001066
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001067 logRecord(AccountsDb.DEBUG_ACTION_AUTHENTICATOR_REMOVE,
1068 AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001069
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001070 accounts.userDataCache.remove(account);
1071 accounts.authTokenCache.remove(account);
1072 accounts.accountTokenCaches.remove(account);
1073 accounts.visibilityCache.remove(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001074
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001075 for (Entry<String, Integer> packageToVisibility :
1076 packagesToVisibility.entrySet()) {
1077 if (packageToVisibility.getValue()
1078 != AccountManager.VISIBILITY_NOT_VISIBLE) {
1079 notifyPackage(packageToVisibility.getKey(), accounts);
1080 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001081 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001082 } else {
1083 ArrayList<String> accountNames = accountNamesByType.get(account.type);
1084 if (accountNames == null) {
1085 accountNames = new ArrayList<>();
1086 accountNamesByType.put(account.type, accountNames);
1087 }
1088 accountNames.add(account.name);
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001089 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001090 }
1091 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
1092 final String accountType = cur.getKey();
1093 final ArrayList<String> accountNames = cur.getValue();
1094 final Account[] accountsForType = new Account[accountNames.size()];
1095 for (int i = 0; i < accountsForType.length; i++) {
1096 accountsForType[i] = new Account(accountNames.get(i), accountType,
1097 UUID.randomUUID().toString());
Fred Quintana56285a62010-12-02 14:20:51 -08001098 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001099 accounts.accountCache.put(accountType, accountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08001100 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001101 accounts.visibilityCache.putAll(accountsDb.findAllVisibilityValues());
1102 } finally {
1103 if (accountDeleted) {
1104 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintana56285a62010-12-02 14:20:51 -08001105 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001106 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001107 }
1108 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001109 }
1110
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001111 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1112 // Get the UIDs of all apps that might have data on the device. We want
1113 // to preserve user data if the app might otherwise be storing data.
1114 List<PackageInfo> pkgsWithData =
1115 mPackageManager.getInstalledPackagesAsUser(
1116 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1117 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1118 for (PackageInfo pkgInfo : pkgsWithData) {
1119 if (pkgInfo.applicationInfo != null
1120 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1121 knownUids.put(pkgInfo.applicationInfo.uid, true);
1122 }
1123 }
1124 return knownUids;
1125 }
1126
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001127 static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001128 Context context,
1129 int userId) {
1130 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001131 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1132 }
1133
1134 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1135 IAccountAuthenticatorCache authCache,
1136 int userId) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08001137 HashMap<String, Integer> knownAuth = new LinkedHashMap<>();
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001138 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1139 .getAllServices(userId)) {
1140 knownAuth.put(service.type.type, service.uid);
1141 }
1142 return knownAuth;
1143 }
1144
Amith Yamasani04e0d262012-02-14 11:50:53 -08001145 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001146 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001147 }
1148
1149 protected UserAccounts getUserAccounts(int userId) {
1150 synchronized (mUsers) {
1151 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001152 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001153 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001154 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1155 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001156 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001157 initializeDebugDbSizeAndCompileSqlStatementForLogging(accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001158 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001159 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001160 validateAccounts = true;
1161 }
1162 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001163 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001164 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001165 synchronized (accounts.dbLock) {
1166 synchronized (accounts.cacheLock) {
1167 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1168 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1169 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001170 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001171 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001172 }
1173 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001174 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001175 }
1176 return accounts;
1177 }
1178 }
1179
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001180 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1181 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001182 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001183 if (!accountsToRemove.isEmpty()) {
1184 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1185 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001186 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1187 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001188
1189 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001190 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001191 }
1192 }
1193 }
1194
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001195 private void purgeOldGrantsAll() {
1196 synchronized (mUsers) {
1197 for (int i = 0; i < mUsers.size(); i++) {
1198 purgeOldGrants(mUsers.valueAt(i));
1199 }
1200 }
1201 }
1202
1203 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001204 synchronized (accounts.dbLock) {
1205 synchronized (accounts.cacheLock) {
1206 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1207 for (int uid : uids) {
1208 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1209 if (packageExists) {
1210 continue;
1211 }
1212 Log.d(TAG, "deleting grants for UID " + uid
1213 + " because its package is no longer installed");
1214 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001215 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001216 }
1217 }
1218 }
1219
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001220 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001221 if (isSpecialPackageKey(packageName)) {
1222 return;
1223 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001224 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001225 int numberOfUsers = mUsers.size();
1226 for (int i = 0; i < numberOfUsers; i++) {
1227 UserAccounts accounts = mUsers.valueAt(i);
1228 try {
1229 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1230 } catch (NameNotFoundException e) {
1231 // package does not exist - remove visibility values
1232 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001233 synchronized (accounts.dbLock) {
1234 synchronized (accounts.cacheLock) {
1235 for (Account account : accounts.visibilityCache.keySet()) {
1236 Map<String, Integer> accountVisibility =
1237 getPackagesAndVisibilityForAccountLocked(account, accounts);
1238 accountVisibility.remove(packageName);
1239 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001240 }
1241 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001242 }
1243 }
1244 }
1245 }
1246
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001247
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -07001248 private void onCleanupUser(int userId) {
1249 Log.i(TAG, "onCleanupUser " + userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001250 UserAccounts accounts;
1251 synchronized (mUsers) {
1252 accounts = mUsers.get(userId);
1253 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001254 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001255 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001256 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001257 synchronized (accounts.dbLock) {
1258 synchronized (accounts.cacheLock) {
1259 accounts.accountsDb.close();
1260 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001261 }
Amith Yamasani13593602012-03-22 16:16:17 -07001262 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001263 }
1264
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001265 @VisibleForTesting
1266 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001267 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1268 }
1269
1270 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001271 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1272 Log.v(TAG, "onUserUnlocked " + userId);
1273 }
1274 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001275 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001276 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001277 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001278 syncSharedAccounts(userId);
1279 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001280
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001281 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001282 // Check if there's a shared account that needs to be created as an account
1283 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1284 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001285 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001286 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001287 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001288 : UserHandle.USER_SYSTEM;
1289 if (parentUserId < 0) {
1290 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1291 return;
1292 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001293 for (Account sa : sharedAccounts) {
1294 if (ArrayUtils.contains(accounts, sa)) continue;
1295 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001296 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001297 }
1298 }
1299
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001300 @Override
1301 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001302 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001303 }
1304
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001305 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001306 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001307 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001308 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1309 Log.v(TAG, "getPassword: " + account
1310 + ", caller's uid " + Binder.getCallingUid()
1311 + ", pid " + Binder.getCallingPid());
1312 }
Fred Quintana382601f2010-03-25 12:25:10 -07001313 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001314 int userId = UserHandle.getCallingUserId();
1315 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001316 String msg = String.format(
1317 "uid %s cannot get secrets for accounts of type: %s",
1318 callingUid,
1319 account.type);
1320 throw new SecurityException(msg);
1321 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001322 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001323 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001324 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001325 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001326 } finally {
1327 restoreCallingIdentity(identityToken);
1328 }
1329 }
1330
Amith Yamasani04e0d262012-02-14 11:50:53 -08001331 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001332 if (account == null) {
1333 return null;
1334 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001335 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001336 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1337 return null;
1338 }
Fred Quintana31957f12009-10-21 13:43:10 -07001339
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001340 synchronized (accounts.dbLock) {
1341 synchronized (accounts.cacheLock) {
1342 return accounts.accountsDb
1343 .findAccountPasswordByNameAndType(account.name, account.type);
1344 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001345 }
1346 }
1347
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001348 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001349 public String getPreviousName(Account account) {
1350 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1351 Log.v(TAG, "getPreviousName: " + account
1352 + ", caller's uid " + Binder.getCallingUid()
1353 + ", pid " + Binder.getCallingPid());
1354 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001355 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001356 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001357 long identityToken = clearCallingIdentity();
1358 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001359 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001360 return readPreviousNameInternal(accounts, account);
1361 } finally {
1362 restoreCallingIdentity(identityToken);
1363 }
1364 }
1365
1366 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1367 if (account == null) {
1368 return null;
1369 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001370 synchronized (accounts.dbLock) {
1371 synchronized (accounts.cacheLock) {
1372 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1373 if (previousNameRef == null) {
1374 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1375 previousNameRef = new AtomicReference<>(previousName);
1376 accounts.previousNameCache.put(account, previousNameRef);
1377 return previousName;
1378 } else {
1379 return previousNameRef.get();
1380 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001381 }
1382 }
1383 }
1384
1385 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001386 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001387 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001388 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001389 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1390 account, key, callingUid, Binder.getCallingPid());
1391 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001392 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001393 Preconditions.checkNotNull(account, "account cannot be null");
1394 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001395 int userId = UserHandle.getCallingUserId();
1396 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001397 String msg = String.format(
1398 "uid %s cannot get user data for accounts of type: %s",
1399 callingUid,
1400 account.type);
1401 throw new SecurityException(msg);
1402 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001403 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001404 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1405 return null;
1406 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001407 long identityToken = clearCallingIdentity();
1408 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001409 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001410 if (!accountExistsCache(accounts, account)) {
1411 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001412 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001413 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001414 } finally {
1415 restoreCallingIdentity(identityToken);
1416 }
1417 }
1418
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001419 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001420 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001421 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001422 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1423 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001424 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001425 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001426 + ", pid " + Binder.getCallingPid());
1427 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001428 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001429 if (isCrossUser(callingUid, userId)) {
1430 throw new SecurityException(
1431 String.format(
1432 "User %s tying to get authenticator types for %s" ,
1433 UserHandle.getCallingUserId(),
1434 userId));
1435 }
1436
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001437 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001438 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001439 return getAuthenticatorTypesInternal(userId);
1440
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001441 } finally {
1442 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001443 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001444 }
1445
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001446 /**
1447 * Should only be called inside of a clearCallingIdentity block.
1448 */
1449 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001450 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001451 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1452 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1453 AuthenticatorDescription[] types =
1454 new AuthenticatorDescription[authenticatorCollection.size()];
1455 int i = 0;
1456 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1457 : authenticatorCollection) {
1458 types[i] = authenticator.type;
1459 i++;
1460 }
1461 return types;
1462 }
1463
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001464 private boolean isCrossUser(int callingUid, int userId) {
1465 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001466 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001467 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001468 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1469 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001470 }
1471
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001472 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001473 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001474 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001475 }
1476
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001477 @Override
1478 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001479 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001480 int callingUid = Binder.getCallingUid();
1481 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1482 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001483 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001484 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001485 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1486 final UserAccounts toAccounts = getUserAccounts(userTo);
1487 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001488 if (response != null) {
1489 Bundle result = new Bundle();
1490 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1491 try {
1492 response.onResult(result);
1493 } catch (RemoteException e) {
1494 Slog.w(TAG, "Failed to report error back to the client." + e);
1495 }
1496 }
1497 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001498 }
1499
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001500 Slog.d(TAG, "Copying account " + account.name
1501 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001502 long identityToken = clearCallingIdentity();
1503 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001504 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001505 false /* stripAuthTokenFromResult */, account.name,
1506 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001507 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001508 protected String toDebugString(long now) {
1509 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1510 + ", " + account.type;
1511 }
1512
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001513 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001514 public void run() throws RemoteException {
1515 mAuthenticator.getAccountCredentialsForCloning(this, account);
1516 }
1517
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001518 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001519 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001520 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001521 if (result != null
1522 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1523 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001524 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001525 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001526 super.onResult(result);
1527 }
1528 }
1529 }.bind();
1530 } finally {
1531 restoreCallingIdentity(identityToken);
1532 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001533 }
1534
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001535 @Override
1536 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001537 final int callingUid = Binder.getCallingUid();
1538 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1539 String msg = String.format(
1540 "accountAuthenticated( account: %s, callerUid: %s)",
1541 account,
1542 callingUid);
1543 Log.v(TAG, msg);
1544 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001545 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001546 int userId = UserHandle.getCallingUserId();
1547 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001548 String msg = String.format(
1549 "uid %s cannot notify authentication for accounts of type: %s",
1550 callingUid,
1551 account.type);
1552 throw new SecurityException(msg);
1553 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001554
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001555 if (!canUserModifyAccounts(userId, callingUid) ||
1556 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001557 return false;
1558 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001559
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001560 long identityToken = clearCallingIdentity();
1561 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001562 UserAccounts accounts = getUserAccounts(userId);
1563 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001564 } finally {
1565 restoreCallingIdentity(identityToken);
1566 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001567 }
1568
1569 private boolean updateLastAuthenticatedTime(Account account) {
1570 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001571 synchronized (accounts.dbLock) {
1572 synchronized (accounts.cacheLock) {
1573 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1574 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001575 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001576 }
1577
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001578 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001579 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1580 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001581 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001582 long id = clearCallingIdentity();
1583 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001584 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001585 false /* stripAuthTokenFromResult */, account.name,
1586 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001587 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001588 protected String toDebugString(long now) {
1589 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1590 + ", " + account.type;
1591 }
1592
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001593 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001594 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001595 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001596 UserAccounts owner = getUserAccounts(parentUserId);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001597 synchronized (owner.dbLock) {
1598 synchronized (owner.cacheLock) {
1599 for (Account acc : getAccounts(parentUserId,
1600 mContext.getOpPackageName())) {
1601 if (acc.equals(account)) {
1602 mAuthenticator.addAccountFromCredentials(
1603 this, account, accountCredentials);
1604 break;
1605 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001606 }
1607 }
1608 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001609 }
1610
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001611 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001612 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001613 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001614 // TODO: Anything to do if if succedded?
1615 // TODO: If it failed: Show error notification? Should we remove the shadow
1616 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001617 // TODO: what we do with the visibility?
1618
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001619 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001620 }
1621
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001622 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001623 public void onError(int errorCode, String errorMessage) {
1624 super.onError(errorCode, errorMessage);
1625 // TODO: Show error notification to user
1626 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1627 }
1628
1629 }.bind();
1630 } finally {
1631 restoreCallingIdentity(id);
1632 }
1633 }
1634
Amith Yamasani04e0d262012-02-14 11:50:53 -08001635 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001636 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001637 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001638 if (account == null) {
1639 return false;
1640 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001641 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001642 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1643 + " is locked. callingUid=" + callingUid);
1644 return false;
1645 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001646 synchronized (accounts.dbLock) {
1647 synchronized (accounts.cacheLock) {
1648 accounts.accountsDb.beginTransaction();
1649 try {
1650 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
1651 Log.w(TAG, "insertAccountIntoDatabase: " + account
1652 + ", skipping since the account already exists");
1653 return false;
1654 }
1655 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1656 if (accountId < 0) {
1657 Log.w(TAG, "insertAccountIntoDatabase: " + account
1658 + ", skipping the DB insert failed");
1659 return false;
1660 }
1661 // Insert into DE table
1662 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
1663 Log.w(TAG, "insertAccountIntoDatabase: " + account
1664 + ", skipping the DB insert failed");
1665 return false;
1666 }
1667 if (extras != null) {
1668 for (String key : extras.keySet()) {
1669 final String value = extras.getString(key);
1670 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
1671 Log.w(TAG, "insertAccountIntoDatabase: " + account
1672 + ", skipping since insertExtra failed for key " + key);
1673 return false;
1674 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001675 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001676 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001677
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001678 if (packageToVisibility != null) {
1679 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1680 setAccountVisibility(account, entry.getKey() /* package */,
1681 entry.getValue() /* visibility */, false /* notify */,
1682 accounts);
1683 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001684 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001685 accounts.accountsDb.setTransactionSuccessful();
1686
1687 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1688 accountId,
1689 accounts, callingUid);
1690
1691 insertAccountIntoCacheLocked(accounts, account);
1692 } finally {
1693 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001694 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001695 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001696 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001697 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1698 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001699 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001700
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001701 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001702 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1703 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001704
Amith Yamasani5be347b2013-03-31 17:44:31 -07001705 return true;
1706 }
1707
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001708 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001709 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001710 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001711 }
1712 }
1713
Amith Yamasani5be347b2013-03-31 17:44:31 -07001714 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001715 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001716 * running, then clone the account too.
1717 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001718 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001719 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001720 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001721 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001722 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001723 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001724 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001725 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001726 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001727 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001728 }
1729 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001730 }
1731 }
1732
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001733 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001734 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001735 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001736 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001737 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001738 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1739 Log.v(TAG, "hasFeatures: " + account
1740 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001741 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001742 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001743 + ", pid " + Binder.getCallingPid());
1744 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001745 Preconditions.checkArgument(account != null, "account cannot be null");
1746 Preconditions.checkArgument(response != null, "response cannot be null");
1747 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001748 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001749 checkReadAccountsPermitted(callingUid, account.type, userId,
1750 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001751
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001752 long identityToken = clearCallingIdentity();
1753 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001754 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001755 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001756 } finally {
1757 restoreCallingIdentity(identityToken);
1758 }
1759 }
1760
1761 private class TestFeaturesSession extends Session {
1762 private final String[] mFeatures;
1763 private final Account mAccount;
1764
Amith Yamasani04e0d262012-02-14 11:50:53 -08001765 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001766 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001767 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001768 true /* stripAuthTokenFromResult */, account.name,
1769 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001770 mFeatures = features;
1771 mAccount = account;
1772 }
1773
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001774 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001775 public void run() throws RemoteException {
1776 try {
1777 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1778 } catch (RemoteException e) {
1779 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1780 }
1781 }
1782
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001783 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001784 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001785 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001786 IAccountManagerResponse response = getResponseAndClose();
1787 if (response != null) {
1788 try {
1789 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001790 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001791 return;
1792 }
Fred Quintana56285a62010-12-02 14:20:51 -08001793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1794 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1795 + response);
1796 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001797 final Bundle newResult = new Bundle();
1798 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1799 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1800 response.onResult(newResult);
1801 } catch (RemoteException e) {
1802 // if the caller is dead then there is no one to care about remote exceptions
1803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1804 Log.v(TAG, "failure while notifying response", e);
1805 }
1806 }
1807 }
1808 }
1809
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001810 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001811 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001812 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001813 + ", " + mAccount
1814 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1815 }
1816 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001817
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001818 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001819 public void renameAccount(
1820 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001821 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001822 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1823 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001824 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001825 + ", pid " + Binder.getCallingPid());
1826 }
1827 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001828 int userId = UserHandle.getCallingUserId();
1829 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001830 String msg = String.format(
1831 "uid %s cannot rename accounts of type: %s",
1832 callingUid,
1833 accountToRename.type);
1834 throw new SecurityException(msg);
1835 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001836 long identityToken = clearCallingIdentity();
1837 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001838 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001839 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001840 Bundle result = new Bundle();
1841 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1842 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001843 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
1844 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001845 try {
1846 response.onResult(result);
1847 } catch (RemoteException e) {
1848 Log.w(TAG, e.getMessage());
1849 }
1850 } finally {
1851 restoreCallingIdentity(identityToken);
1852 }
1853 }
1854
1855 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001856 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001857 Account resultAccount = null;
1858 /*
1859 * Cancel existing notifications. Let authenticators
1860 * re-post notifications as required. But we don't know if
1861 * the authenticators have bound their notifications to
1862 * now stale account name data.
1863 *
1864 * With a rename api, we might not need to do this anymore but it
1865 * shouldn't hurt.
1866 */
1867 cancelNotification(
1868 getSigninRequiredNotificationId(accounts, accountToRename),
1869 new UserHandle(accounts.userId));
1870 synchronized(accounts.credentialsPermissionNotificationIds) {
1871 for (Pair<Pair<Account, String>, Integer> pair:
1872 accounts.credentialsPermissionNotificationIds.keySet()) {
1873 if (accountToRename.equals(pair.first.first)) {
1874 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1875 cancelNotification(id, new UserHandle(accounts.userId));
1876 }
1877 }
1878 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001879 synchronized (accounts.dbLock) {
1880 synchronized (accounts.cacheLock) {
1881 accounts.accountsDb.beginTransaction();
1882 Account renamedAccount = new Account(newName, accountToRename.type);
1883 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
1884 Log.e(TAG, "renameAccount failed - account with new name already exists");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001885 return null;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001886 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001887 try {
1888 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
1889 if (accountId >= 0) {
1890 accounts.accountsDb.renameCeAccount(accountId, newName);
1891 if (accounts.accountsDb.renameDeAccount(
1892 accountId, newName, accountToRename.name)) {
1893 accounts.accountsDb.setTransactionSuccessful();
1894 } else {
1895 Log.e(TAG, "renameAccount failed");
1896 return null;
1897 }
1898 } else {
1899 Log.e(TAG, "renameAccount failed - old account does not exist");
1900 return null;
1901 }
1902 } finally {
1903 accounts.accountsDb.endTransaction();
1904 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001905 /*
1906 * Database transaction was successful. Clean up cached
1907 * data associated with the account in the user profile.
1908 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001909 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001910 /*
1911 * Extract the data and token caches before removing the
1912 * old account to preserve the user data associated with
1913 * the account.
1914 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001915 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1916 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1917 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
1918 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001919 /*
1920 * Update the cached data associated with the renamed
1921 * account.
1922 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001923 accounts.userDataCache.put(renamedAccount, tmpData);
1924 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1925 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
1926 accounts.previousNameCache.put(
1927 renamedAccount,
1928 new AtomicReference<>(accountToRename.name));
1929 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001930
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001931 int parentUserId = accounts.userId;
1932 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001933 /*
1934 * Owner or system user account was renamed, rename the account for
1935 * those users with which the account was shared.
1936 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001937 List<UserInfo> users = getUserManager().getUsers(true);
1938 for (UserInfo user : users) {
1939 if (user.isRestricted()
1940 && (user.restrictedProfileParentId == parentUserId)) {
1941 renameSharedAccountAsUser(accountToRename, newName, user.id);
1942 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001943 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001944 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001945
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001946 sendNotificationAccountUpdated(resultAccount, accounts);
1947 sendAccountsChangedBroadcast(accounts.userId);
1948 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001949 }
1950 return resultAccount;
1951 }
1952
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001953 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001954 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001955 return userInfo != null && userInfo.canHaveProfile();
1956 }
1957
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001958 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001959 public void removeAccount(IAccountManagerResponse response, Account account,
1960 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001961 removeAccountAsUser(
1962 response,
1963 account,
1964 expectActivityLaunch,
1965 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001966 }
1967
1968 @Override
1969 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001970 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001971 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001972 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1973 Log.v(TAG, "removeAccount: " + account
1974 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001975 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001976 + ", pid " + Binder.getCallingPid()
1977 + ", for user id " + userId);
1978 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001979 Preconditions.checkArgument(account != null, "account cannot be null");
1980 Preconditions.checkArgument(response != null, "response cannot be null");
1981
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001982 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001983 if (isCrossUser(callingUid, userId)) {
1984 throw new SecurityException(
1985 String.format(
1986 "User %s tying remove account for %s" ,
1987 UserHandle.getCallingUserId(),
1988 userId));
1989 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001990 /*
1991 * Only the system or authenticator should be allowed to remove accounts for that
1992 * authenticator. This will let users remove accounts (via Settings in the system) but not
1993 * arbitrary applications (like competing authenticators).
1994 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001995 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001996 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1997 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001998 String msg = String.format(
1999 "uid %s cannot remove accounts of type: %s",
2000 callingUid,
2001 account.type);
2002 throw new SecurityException(msg);
2003 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002004 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002005 try {
2006 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2007 "User cannot modify accounts");
2008 } catch (RemoteException re) {
2009 }
2010 return;
2011 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002012 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002013 try {
2014 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2015 "User cannot modify accounts of this type (policy).");
2016 } catch (RemoteException re) {
2017 }
2018 return;
2019 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002020 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002021 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002022 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002023 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002024 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002025 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002026 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002027 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002028 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002029 }
2030 }
2031 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002032 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002033 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002034 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2035 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002036 accountId,
2037 accounts,
2038 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002039 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002040 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2041 } finally {
2042 restoreCallingIdentity(identityToken);
2043 }
2044 }
2045
2046 @Override
2047 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002048 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2050 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002051 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002052 + ", pid " + Binder.getCallingPid());
2053 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002054 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002055 if (account == null) {
2056 /*
2057 * Null accounts should result in returning false, as per
2058 * AccountManage.addAccountExplicitly(...) java doc.
2059 */
2060 Log.e(TAG, "account is null");
2061 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002062 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002063 String msg = String.format(
2064 "uid %s cannot explicitly add accounts of type: %s",
2065 callingUid,
2066 account.type);
2067 throw new SecurityException(msg);
2068 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002069 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002070 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002071 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002072 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2073 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002074 accountId,
2075 accounts,
2076 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002077 long identityToken = clearCallingIdentity();
2078 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002079 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002080 } finally {
2081 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002082 }
Fred Quintana60307342009-03-24 22:48:12 -07002083 }
2084
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002085 private class RemoveAccountSession extends Session {
2086 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002087 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002088 Account account, boolean expectActivityLaunch) {
2089 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002090 true /* stripAuthTokenFromResult */, account.name,
2091 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002092 mAccount = account;
2093 }
2094
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002095 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002096 protected String toDebugString(long now) {
2097 return super.toDebugString(now) + ", removeAccount"
2098 + ", account " + mAccount;
2099 }
2100
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002101 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002102 public void run() throws RemoteException {
2103 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2104 }
2105
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002106 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002107 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002108 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002109 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2110 && !result.containsKey(AccountManager.KEY_INTENT)) {
2111 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002112 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002113 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002114 }
2115 IAccountManagerResponse response = getResponseAndClose();
2116 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002117 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2118 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2119 + response);
2120 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002121 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002122 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002123 try {
2124 response.onResult(result2);
2125 } catch (RemoteException e) {
2126 // ignore
2127 }
2128 }
2129 }
2130 super.onResult(result);
2131 }
2132 }
2133
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002134 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002135 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002136 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002137 }
2138
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002139 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002140 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002141 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002142 if (!userUnlocked) {
2143 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2144 + " is still locked. CE data will be removed later");
2145 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002146 synchronized (accounts.dbLock) {
2147 synchronized (accounts.cacheLock) {
2148 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2149 accounts);
2150 accounts.accountsDb.beginTransaction();
2151 // Set to a dummy value, this will only be used if the database
2152 // transaction succeeds.
2153 long accountId = -1;
2154 try {
2155 accountId = accounts.accountsDb.findDeAccountId(account);
2156 if (accountId >= 0) {
2157 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002158 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002159 // always delete from CE table if CE storage is available
2160 // DE account could be removed while CE was locked
2161 if (userUnlocked) {
2162 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2163 if (ceAccountId >= 0) {
2164 accounts.accountsDb.deleteCeAccount(ceAccountId);
2165 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002166 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002167 accounts.accountsDb.setTransactionSuccessful();
2168 } finally {
2169 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002170 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002171 if (isChanged) {
2172 removeAccountFromCacheLocked(accounts, account);
2173 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2174 .entrySet()) {
2175 if (packageToVisibility.getValue()
2176 != AccountManager.VISIBILITY_NOT_VISIBLE) {
2177 notifyPackage(packageToVisibility.getKey(), accounts);
2178 }
2179 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002180
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002181 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2182 sendAccountsChangedBroadcast(accounts.userId);
2183 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2184 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2185 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2186 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002187 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002188 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002189 long id = Binder.clearCallingIdentity();
2190 try {
2191 int parentUserId = accounts.userId;
2192 if (canHaveProfile(parentUserId)) {
2193 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002194 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002195 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002196 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002197 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002198 }
2199 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002200 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002201 } finally {
2202 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002203 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002204
2205 if (isChanged) {
2206 synchronized (accounts.credentialsPermissionNotificationIds) {
2207 for (Pair<Pair<Account, String>, Integer> key
2208 : accounts.credentialsPermissionNotificationIds.keySet()) {
2209 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002210 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002211 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002212 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002213 account, uid, false));
2214 }
2215 }
2216 }
2217 }
2218
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002219 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002220 }
2221
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002222 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002223 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002224 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002225 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2226 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002227 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2228 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002229 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002230 + ", pid " + Binder.getCallingPid());
2231 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002232 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002233 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002234 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002235 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002236 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002237 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002238 accounts.accountsDb.beginTransaction();
2239 try {
2240 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2241 accounts.accountsDb.setTransactionSuccessful();
2242 } finally {
2243 accounts.accountsDb.endTransaction();
2244 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002245 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002246 for (Pair<Account, String> tokenInfo : deletedTokens) {
2247 Account act = tokenInfo.first;
2248 String tokenType = tokenInfo.second;
2249 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002250 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002251 // wipe out cached token in memory.
2252 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002253 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002254 }
Fred Quintana60307342009-03-24 22:48:12 -07002255 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002256 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002257 }
2258 }
2259
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002260 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002261 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002262 // TODO Move to AccountsDB
2263 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002264 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002265
Fred Quintana33269202009-04-20 16:05:10 -07002266 try {
2267 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002268 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002269 String accountName = cursor.getString(1);
2270 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002271 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002272 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002273 }
Fred Quintana33269202009-04-20 16:05:10 -07002274 } finally {
2275 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002276 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002277 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002278 }
2279
Carlos Valdivia91979be2015-05-22 14:11:35 -07002280 private void saveCachedToken(
2281 UserAccounts accounts,
2282 Account account,
2283 String callerPkg,
2284 byte[] callerSigDigest,
2285 String tokenType,
2286 String token,
2287 long expiryMillis) {
2288
2289 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2290 return;
2291 }
2292 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002293 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002294 synchronized (accounts.cacheLock) {
2295 accounts.accountTokenCaches.put(
2296 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002297 }
2298 }
2299
Amith Yamasani04e0d262012-02-14 11:50:53 -08002300 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2301 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002302 if (account == null || type == null) {
2303 return false;
2304 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002305 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002306 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002307 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002308 accounts.accountsDb.beginTransaction();
2309 boolean updateCache = false;
2310 try {
2311 long accountId = accounts.accountsDb.findDeAccountId(account);
2312 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002313 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002314 }
2315 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2316 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2317 accounts.accountsDb.setTransactionSuccessful();
2318 updateCache = true;
2319 return true;
2320 }
2321 return false;
2322 } finally {
2323 accounts.accountsDb.endTransaction();
2324 if (updateCache) {
2325 synchronized (accounts.cacheLock) {
2326 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2327 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002328 }
Fred Quintana33269202009-04-20 16:05:10 -07002329 }
Fred Quintana60307342009-03-24 22:48:12 -07002330 }
2331 }
2332
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002333 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002334 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002335 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002336 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2337 Log.v(TAG, "peekAuthToken: " + account
2338 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002339 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002340 + ", pid " + Binder.getCallingPid());
2341 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002342 Preconditions.checkNotNull(account, "account cannot be null");
2343 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002344 int userId = UserHandle.getCallingUserId();
2345 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002346 String msg = String.format(
2347 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2348 callingUid,
2349 account.type);
2350 throw new SecurityException(msg);
2351 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002352 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002353 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2354 + callingUid);
2355 return null;
2356 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002357 long identityToken = clearCallingIdentity();
2358 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002359 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002360 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002361 } finally {
2362 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002363 }
Fred Quintana60307342009-03-24 22:48:12 -07002364 }
2365
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002366 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002367 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002368 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002369 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2370 Log.v(TAG, "setAuthToken: " + account
2371 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002372 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002373 + ", pid " + Binder.getCallingPid());
2374 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002375 Preconditions.checkNotNull(account, "account cannot be null");
2376 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002377 int userId = UserHandle.getCallingUserId();
2378 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002379 String msg = String.format(
2380 "uid %s cannot set auth tokens associated with accounts of type: %s",
2381 callingUid,
2382 account.type);
2383 throw new SecurityException(msg);
2384 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002385 long identityToken = clearCallingIdentity();
2386 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002387 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002388 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002389 } finally {
2390 restoreCallingIdentity(identityToken);
2391 }
Fred Quintana60307342009-03-24 22:48:12 -07002392 }
2393
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002394 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002395 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002396 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002397 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2398 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002399 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002400 + ", pid " + Binder.getCallingPid());
2401 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002402 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002403 int userId = UserHandle.getCallingUserId();
2404 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002405 String msg = String.format(
2406 "uid %s cannot set secrets for accounts of type: %s",
2407 callingUid,
2408 account.type);
2409 throw new SecurityException(msg);
2410 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002411 long identityToken = clearCallingIdentity();
2412 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002413 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002414 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002415 } finally {
2416 restoreCallingIdentity(identityToken);
2417 }
Fred Quintana60307342009-03-24 22:48:12 -07002418 }
2419
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002420 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2421 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002422 if (account == null) {
2423 return;
2424 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002425 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002426 synchronized (accounts.dbLock) {
2427 synchronized (accounts.cacheLock) {
2428 accounts.accountsDb.beginTransaction();
2429 try {
2430 final long accountId = accounts.accountsDb.findDeAccountId(account);
2431 if (accountId >= 0) {
2432 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2433 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2434 accounts.authTokenCache.remove(account);
2435 accounts.accountTokenCaches.remove(account);
2436 accounts.accountsDb.setTransactionSuccessful();
2437 // If there is an account whose password will be updated and the database
2438 // transactions succeed, then we say that a change has occured. Even if the
2439 // new password is the same as the old and there were no authtokens to
2440 // delete.
2441 isChanged = true;
2442 String action = (password == null || password.length() == 0) ?
2443 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2444 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2445 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2446 callingUid);
2447 }
2448 } finally {
2449 accounts.accountsDb.endTransaction();
2450 if (isChanged) {
2451 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2452 sendNotificationAccountUpdated(account, accounts);
2453 sendAccountsChangedBroadcast(accounts.userId);
2454 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002455 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002456 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002457 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002458 }
2459
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002460 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002461 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002462 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002463 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2464 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002465 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002466 + ", pid " + Binder.getCallingPid());
2467 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002468 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002469 int userId = UserHandle.getCallingUserId();
2470 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002471 String msg = String.format(
2472 "uid %s cannot clear passwords for accounts of type: %s",
2473 callingUid,
2474 account.type);
2475 throw new SecurityException(msg);
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);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002480 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002481 } finally {
2482 restoreCallingIdentity(identityToken);
2483 }
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 setUserData(Account account, String key, String value) {
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, "setUserData: " + account
2491 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002492 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002493 + ", pid " + Binder.getCallingPid());
2494 }
Fred Quintana382601f2010-03-25 12:25:10 -07002495 if (key == null) throw new IllegalArgumentException("key is null");
2496 if (account == null) throw new IllegalArgumentException("account is 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 user data for 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();
Fred Quintana60307342009-03-24 22:48:12 -07002506 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002507 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002508 if (!accountExistsCache(accounts, account)) {
2509 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002510 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002511 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002512 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002513 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002514 }
2515 }
2516
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002517 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2518 synchronized (accounts.cacheLock) {
2519 if (accounts.accountCache.containsKey(account.type)) {
2520 for (Account acc : accounts.accountCache.get(account.type)) {
2521 if (acc.name.equals(account.name)) {
2522 return true;
2523 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002524 }
2525 }
2526 }
2527 return false;
2528 }
2529
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002530 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002531 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002532 synchronized (accounts.dbLock) {
2533 accounts.accountsDb.beginTransaction();
2534 try {
2535 long accountId = accounts.accountsDb.findDeAccountId(account);
2536 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002537 return;
2538 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002539 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2540 if (extrasId < 0) {
2541 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2542 if (extrasId < 0) {
2543 return;
2544 }
2545 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2546 return;
2547 }
2548 accounts.accountsDb.setTransactionSuccessful();
2549 } finally {
2550 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002551 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002552 synchronized (accounts.cacheLock) {
2553 writeUserDataIntoCacheLocked(accounts, account, key, value);
2554 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002555 }
2556 }
2557
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002558 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002559 if (result == null) {
2560 Log.e(TAG, "the result is unexpectedly null", new Exception());
2561 }
2562 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2563 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2564 + response);
2565 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002566 try {
2567 response.onResult(result);
2568 } catch (RemoteException e) {
2569 // if the caller is dead then there is no one to care about remote
2570 // exceptions
2571 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2572 Log.v(TAG, "failure while notifying response", e);
2573 }
2574 }
2575 }
2576
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002577 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002578 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2579 final String authTokenType)
2580 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002581 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2582 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002583
Fred Quintanad9640ec2012-05-23 12:37:00 -07002584 final int callingUid = getCallingUid();
2585 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002586 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002587 throw new SecurityException("can only call from system");
2588 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002589 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002590 long identityToken = clearCallingIdentity();
2591 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002592 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002593 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2594 false /* stripAuthTokenFromResult */, null /* accountName */,
2595 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002596 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002597 protected String toDebugString(long now) {
2598 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002599 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002600 + ", authTokenType " + authTokenType;
2601 }
2602
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002603 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002604 public void run() throws RemoteException {
2605 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2606 }
2607
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002608 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002609 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002610 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002611 if (result != null) {
2612 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2613 Bundle bundle = new Bundle();
2614 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2615 super.onResult(bundle);
2616 return;
2617 } else {
2618 super.onResult(result);
2619 }
2620 }
2621 }.bind();
2622 } finally {
2623 restoreCallingIdentity(identityToken);
2624 }
2625 }
2626
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002627 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002628 public void getAuthToken(
2629 IAccountManagerResponse response,
2630 final Account account,
2631 final String authTokenType,
2632 final boolean notifyOnAuthFailure,
2633 final boolean expectActivityLaunch,
2634 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002635 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002636 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2637 Log.v(TAG, "getAuthToken: " + account
2638 + ", response " + response
2639 + ", authTokenType " + authTokenType
2640 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2641 + ", expectActivityLaunch " + expectActivityLaunch
2642 + ", caller's uid " + Binder.getCallingUid()
2643 + ", pid " + Binder.getCallingPid());
2644 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002645 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002646 try {
2647 if (account == null) {
2648 Slog.w(TAG, "getAuthToken called with null account");
2649 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2650 return;
2651 }
2652 if (authTokenType == null) {
2653 Slog.w(TAG, "getAuthToken called with null authTokenType");
2654 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2655 return;
2656 }
2657 } catch (RemoteException e) {
2658 Slog.w(TAG, "Failed to report error back to the client." + e);
2659 return;
2660 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002661 int userId = UserHandle.getCallingUserId();
2662 long ident = Binder.clearCallingIdentity();
2663 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002664 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002665 try {
2666 accounts = getUserAccounts(userId);
2667 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2668 AuthenticatorDescription.newKey(account.type), accounts.userId);
2669 } finally {
2670 Binder.restoreCallingIdentity(ident);
2671 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002672
Costin Manolachea40c6302010-12-13 14:50:45 -08002673 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002674 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002675
2676 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002677 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002678 final boolean permissionGranted =
2679 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002680
Carlos Valdivia91979be2015-05-22 14:11:35 -07002681 // Get the calling package. We will use it for the purpose of caching.
2682 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002683 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002684 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002685 try {
2686 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2687 } finally {
2688 Binder.restoreCallingIdentity(ident);
2689 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002690 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2691 String msg = String.format(
2692 "Uid %s is attempting to illegally masquerade as package %s!",
2693 callerUid,
2694 callerPkg);
2695 throw new SecurityException(msg);
2696 }
2697
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002698 // let authenticator know the identity of the caller
2699 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2700 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002701
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002702 if (notifyOnAuthFailure) {
2703 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002704 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002705
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002706 long identityToken = clearCallingIdentity();
2707 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002708 // Distill the caller's package signatures into a single digest.
2709 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2710
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002711 // if the caller has permission, do the peek. otherwise go the more expensive
2712 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002713 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002714 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002715 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002716 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002717 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2718 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2719 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002720 onResult(response, result);
2721 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002722 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002723 }
2724
Carlos Valdivia91979be2015-05-22 14:11:35 -07002725 if (customTokens) {
2726 /*
2727 * Look up tokens in the new cache only if the loginOptions don't have parameters
2728 * outside of those expected to be injected by the AccountManager, e.g.
2729 * ANDORID_PACKAGE_NAME.
2730 */
2731 String token = readCachedTokenInternal(
2732 accounts,
2733 account,
2734 authTokenType,
2735 callerPkg,
2736 callerPkgSigDigest);
2737 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002738 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2739 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2740 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002741 Bundle result = new Bundle();
2742 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2743 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2744 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2745 onResult(response, result);
2746 return;
2747 }
2748 }
2749
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002750 new Session(
2751 accounts,
2752 response,
2753 account.type,
2754 expectActivityLaunch,
2755 false /* stripAuthTokenFromResult */,
2756 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002757 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002758 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002759 protected String toDebugString(long now) {
2760 if (loginOptions != null) loginOptions.keySet();
2761 return super.toDebugString(now) + ", getAuthToken"
2762 + ", " + account
2763 + ", authTokenType " + authTokenType
2764 + ", loginOptions " + loginOptions
2765 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2766 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002767
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002768 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002769 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002770 // If the caller doesn't have permission then create and return the
2771 // "grant permission" intent instead of the "getAuthToken" intent.
2772 if (!permissionGranted) {
2773 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2774 } else {
2775 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2776 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002777 }
2778
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002779 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002780 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002781 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002782 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002783 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002784 Intent intent = newGrantCredentialsPermissionIntent(
2785 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002786 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002787 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002788 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002789 authTokenType,
2790 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002791 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002792 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002793 onResult(bundle);
2794 return;
2795 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002796 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002797 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002798 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2799 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002800 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002801 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002802 "the type and name should not be empty");
2803 return;
2804 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002805 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002806 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002807 saveAuthTokenToDatabase(
2808 mAccounts,
2809 resultAccount,
2810 authTokenType,
2811 authToken);
2812 }
2813 long expiryMillis = result.getLong(
2814 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2815 if (customTokens
2816 && expiryMillis > System.currentTimeMillis()) {
2817 saveCachedToken(
2818 mAccounts,
2819 account,
2820 callerPkg,
2821 callerPkgSigDigest,
2822 authTokenType,
2823 authToken,
2824 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002825 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002826 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002827
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002828 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002829 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002830 /*
2831 * Make sure that the supplied intent is owned by the authenticator
2832 * giving it to the system. Otherwise a malicious authenticator could
2833 * have users launching arbitrary activities by tricking users to
2834 * interact with malicious notifications.
2835 */
2836 checkKeyIntent(
2837 Binder.getCallingUid(),
2838 intent);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002839 doNotification(
2840 mAccounts,
2841 account,
2842 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002843 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002844 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002845 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002846 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002847 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002848 }.bind();
2849 } finally {
2850 restoreCallingIdentity(identityToken);
2851 }
Fred Quintana60307342009-03-24 22:48:12 -07002852 }
2853
Carlos Valdivia91979be2015-05-22 14:11:35 -07002854 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2855 MessageDigest digester;
2856 try {
2857 digester = MessageDigest.getInstance("SHA-256");
2858 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2859 callerPkg, PackageManager.GET_SIGNATURES);
2860 for (Signature sig : pkgInfo.signatures) {
2861 digester.update(sig.toByteArray());
2862 }
2863 } catch (NoSuchAlgorithmException x) {
2864 Log.wtf(TAG, "SHA-256 should be available", x);
2865 digester = null;
2866 } catch (NameNotFoundException e) {
2867 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2868 digester = null;
2869 }
2870 return (digester == null) ? null : digester.digest();
2871 }
2872
Dianne Hackborn41203752012-08-31 14:05:51 -07002873 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002874 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002875 int uid = intent.getIntExtra(
2876 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2877 String authTokenType = intent.getStringExtra(
2878 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002879 final String titleAndSubtitle =
2880 mContext.getString(R.string.permission_request_notification_with_subtitle,
2881 account.name);
2882 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002883 String title = titleAndSubtitle;
2884 String subtitle = "";
2885 if (index > 0) {
2886 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002887 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002888 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002889 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002890 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05002891 Notification n =
2892 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
2893 .setSmallIcon(android.R.drawable.stat_sys_warning)
2894 .setWhen(0)
2895 .setColor(contextForUser.getColor(
2896 com.android.internal.R.color.system_notification_accent_color))
2897 .setContentTitle(title)
2898 .setContentText(subtitle)
2899 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2900 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2901 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002902 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002903 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002904 }
2905
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002906 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
2907 int uid, AccountAuthenticatorResponse response, String authTokenType,
2908 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002909
2910 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002911
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002912 if (startInNewTask) {
2913 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
2914 // Since it was set in Eclair+ we can't change it without breaking apps using
2915 // the intent from a non-Activity context. This is the default behavior.
2916 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2917 }
2918 intent.addCategory(String.valueOf(getCredentialPermissionNotificationId(account,
2919 authTokenType, uid) + (packageName != null ? packageName : "")));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002920 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002921 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2922 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002923 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002924
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002925 return intent;
2926 }
2927
2928 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2929 int uid) {
2930 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002931 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002932 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002933 final Pair<Pair<Account, String>, Integer> key =
2934 new Pair<Pair<Account, String>, Integer>(
2935 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002936 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002937 if (id == null) {
2938 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002939 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002940 }
2941 }
2942 return id;
2943 }
2944
Amith Yamasani04e0d262012-02-14 11:50:53 -08002945 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002946 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002947 synchronized (accounts.signinRequiredNotificationIds) {
2948 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002949 if (id == null) {
2950 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002951 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002952 }
2953 }
2954 return id;
2955 }
2956
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002957 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002958 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002959 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002960 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002961 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2963 Log.v(TAG, "addAccount: accountType " + accountType
2964 + ", response " + response
2965 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002966 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08002967 + ", expectActivityLaunch " + expectActivityLaunch
2968 + ", caller's uid " + Binder.getCallingUid()
2969 + ", pid " + Binder.getCallingPid());
2970 }
Fred Quintana382601f2010-03-25 12:25:10 -07002971 if (response == null) throw new IllegalArgumentException("response is null");
2972 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002973
Amith Yamasani71e6c692013-03-24 17:39:28 -07002974 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002975 final int uid = Binder.getCallingUid();
2976 final int userId = UserHandle.getUserId(uid);
2977 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002978 try {
2979 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2980 "User is not allowed to add an account!");
2981 } catch (RemoteException re) {
2982 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002983 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002984 return;
2985 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002986 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002987 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002988 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2989 "User cannot modify accounts of this type (policy).");
2990 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002991 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002992 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2993 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002994 return;
2995 }
2996
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002997 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002998 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2999 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3000 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3001
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003002 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003003 long identityToken = clearCallingIdentity();
3004 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003005 UserAccounts accounts = getUserAccounts(usrId);
3006 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003007 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3008 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003009 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003010 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003011 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003012 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003013 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003014 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003015 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003016 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003017
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003018 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003019 protected String toDebugString(long now) {
3020 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003021 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003022 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003023 }
3024 }.bind();
3025 } finally {
3026 restoreCallingIdentity(identityToken);
3027 }
Fred Quintana60307342009-03-24 22:48:12 -07003028 }
3029
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003030 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003031 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3032 final String authTokenType, final String[] requiredFeatures,
3033 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003034 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003035 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003036 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3037 Log.v(TAG, "addAccount: accountType " + accountType
3038 + ", response " + response
3039 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003040 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003041 + ", expectActivityLaunch " + expectActivityLaunch
3042 + ", caller's uid " + Binder.getCallingUid()
3043 + ", pid " + Binder.getCallingPid()
3044 + ", for user id " + userId);
3045 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003046 Preconditions.checkArgument(response != null, "response cannot be null");
3047 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003048 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003049 if (isCrossUser(callingUid, userId)) {
3050 throw new SecurityException(
3051 String.format(
3052 "User %s trying to add account for %s" ,
3053 UserHandle.getCallingUserId(),
3054 userId));
3055 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003056
3057 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003058 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003059 try {
3060 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3061 "User is not allowed to add an account!");
3062 } catch (RemoteException re) {
3063 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003064 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003065 return;
3066 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003067 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003068 try {
3069 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3070 "User cannot modify accounts of this type (policy).");
3071 } catch (RemoteException re) {
3072 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003073 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3074 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003075 return;
3076 }
3077
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003078 final int pid = Binder.getCallingPid();
3079 final int uid = Binder.getCallingUid();
3080 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3081 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3082 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3083
3084 long identityToken = clearCallingIdentity();
3085 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003086 UserAccounts accounts = getUserAccounts(userId);
3087 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003088 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3089 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003090 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003091 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003092 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003093 @Override
3094 public void run() throws RemoteException {
3095 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3096 options);
3097 }
3098
3099 @Override
3100 protected String toDebugString(long now) {
3101 return super.toDebugString(now) + ", addAccount"
3102 + ", accountType " + accountType
3103 + ", requiredFeatures "
3104 + (requiredFeatures != null
3105 ? TextUtils.join(",", requiredFeatures)
3106 : null);
3107 }
3108 }.bind();
3109 } finally {
3110 restoreCallingIdentity(identityToken);
3111 }
3112 }
3113
Sandra Kwan78812282015-11-04 11:19:47 -08003114 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003115 public void startAddAccountSession(
3116 final IAccountManagerResponse response,
3117 final String accountType,
3118 final String authTokenType,
3119 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003120 final boolean expectActivityLaunch,
3121 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003122 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003123 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3124 Log.v(TAG,
3125 "startAddAccountSession: accountType " + accountType
3126 + ", response " + response
3127 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003128 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003129 + ", expectActivityLaunch " + expectActivityLaunch
3130 + ", caller's uid " + Binder.getCallingUid()
3131 + ", pid " + Binder.getCallingPid());
3132 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003133 Preconditions.checkArgument(response != null, "response cannot be null");
3134 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003135
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003136 final int uid = Binder.getCallingUid();
3137 final int userId = UserHandle.getUserId(uid);
3138 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003139 try {
3140 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3141 "User is not allowed to add an account!");
3142 } catch (RemoteException re) {
3143 }
3144 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3145 return;
3146 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003147 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003148 try {
3149 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3150 "User cannot modify accounts of this type (policy).");
3151 } catch (RemoteException re) {
3152 }
3153 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3154 userId);
3155 return;
3156 }
Sandra Kwan78812282015-11-04 11:19:47 -08003157 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003158 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3159 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3160 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3161
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003162 // Check to see if the Password should be included to the caller.
3163 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3164 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003165 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003166
Sandra Kwan78812282015-11-04 11:19:47 -08003167 long identityToken = clearCallingIdentity();
3168 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003169 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003170 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3171 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003172 new StartAccountSession(
3173 accounts,
3174 response,
3175 accountType,
3176 expectActivityLaunch,
3177 null /* accountName */,
3178 false /* authDetailsRequired */,
3179 true /* updateLastAuthenticationTime */,
3180 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003181 @Override
3182 public void run() throws RemoteException {
3183 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3184 requiredFeatures, options);
3185 }
3186
3187 @Override
3188 protected String toDebugString(long now) {
3189 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3190 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3191 + accountType + ", requiredFeatures "
3192 + (requiredFeatures != null ? requiredFeaturesStr : null);
3193 }
3194 }.bind();
3195 } finally {
3196 restoreCallingIdentity(identityToken);
3197 }
3198 }
3199
3200 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3201 private abstract class StartAccountSession extends Session {
3202
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003203 private final boolean mIsPasswordForwardingAllowed;
3204
3205 public StartAccountSession(
3206 UserAccounts accounts,
3207 IAccountManagerResponse response,
3208 String accountType,
3209 boolean expectActivityLaunch,
3210 String accountName,
3211 boolean authDetailsRequired,
3212 boolean updateLastAuthenticationTime,
3213 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003214 super(accounts, response, accountType, expectActivityLaunch,
3215 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3216 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003217 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003218 }
3219
3220 @Override
3221 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003222 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003223 mNumResults++;
3224 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003225 if (result != null
3226 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003227 checkKeyIntent(
3228 Binder.getCallingUid(),
3229 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08003230 }
Sandra Kwan78812282015-11-04 11:19:47 -08003231 IAccountManagerResponse response;
3232 if (mExpectActivityLaunch && result != null
3233 && result.containsKey(AccountManager.KEY_INTENT)) {
3234 response = mResponse;
3235 } else {
3236 response = getResponseAndClose();
3237 }
3238 if (response == null) {
3239 return;
3240 }
3241 if (result == null) {
3242 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3243 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3244 + response);
3245 }
3246 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3247 "null bundle returned");
3248 return;
3249 }
3250
3251 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3252 // All AccountManager error codes are greater
3253 // than 0
3254 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3255 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3256 return;
3257 }
3258
Hongming Jin368aa192016-07-29 14:29:54 -07003259 // Omit passwords if the caller isn't permitted to see them.
3260 if (!mIsPasswordForwardingAllowed) {
3261 result.remove(AccountManager.KEY_PASSWORD);
3262 }
3263
Sandra Kwan78812282015-11-04 11:19:47 -08003264 // Strip auth token from result.
3265 result.remove(AccountManager.KEY_AUTHTOKEN);
3266
3267 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3268 Log.v(TAG,
3269 getClass().getSimpleName() + " calling onResult() on response " + response);
3270 }
3271
3272 // Get the session bundle created by authenticator. The
3273 // bundle contains data necessary for finishing the session
3274 // later. The session bundle will be encrypted here and
3275 // decrypted later when trying to finish the session.
3276 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3277 if (sessionBundle != null) {
3278 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3279 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003280 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003281 Log.w(TAG, "Account type in session bundle doesn't match request.");
3282 }
3283 // Add accountType info to session bundle. This will
3284 // override any value set by authenticator.
3285 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3286
3287 // Encrypt session bundle before returning to caller.
3288 try {
3289 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3290 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3291 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3292 } catch (GeneralSecurityException e) {
3293 if (Log.isLoggable(TAG, Log.DEBUG)) {
3294 Log.v(TAG, "Failed to encrypt session bundle!", e);
3295 }
3296 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3297 "failed to encrypt session bundle");
3298 return;
3299 }
3300 }
3301
3302 sendResponse(response, result);
3303 }
3304 }
3305
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003306 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003307 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003308 @NonNull Bundle sessionBundle,
3309 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003310 Bundle appInfo,
3311 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003312 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003313 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003314 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3315 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003316 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003317 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003318 + ", caller's uid " + callingUid
3319 + ", caller's user id " + UserHandle.getCallingUserId()
3320 + ", pid " + Binder.getCallingPid()
3321 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003322 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003323 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003324 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3325 // Account type is added to it before encryption.
3326 if (sessionBundle == null || sessionBundle.size() == 0) {
3327 throw new IllegalArgumentException("sessionBundle is empty");
3328 }
3329
Dmitry Dementyev52745472016-12-02 10:27:45 -08003330 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003331 if (isCrossUser(callingUid, userId)) {
3332 throw new SecurityException(
3333 String.format(
3334 "User %s trying to finish session for %s without cross user permission",
3335 UserHandle.getCallingUserId(),
3336 userId));
3337 }
3338
Sandra Kwan0b84b452016-01-20 15:25:42 -08003339 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003340 sendErrorResponse(response,
3341 AccountManager.ERROR_CODE_USER_RESTRICTED,
3342 "User is not allowed to add an account!");
3343 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3344 return;
3345 }
3346
3347 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003348 final Bundle decryptedBundle;
3349 final String accountType;
3350 // First decrypt session bundle to get account type for checking permission.
3351 try {
3352 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3353 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3354 if (decryptedBundle == null) {
3355 sendErrorResponse(
3356 response,
3357 AccountManager.ERROR_CODE_BAD_REQUEST,
3358 "failed to decrypt session bundle");
3359 return;
3360 }
3361 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3362 // Account type cannot be null. This should not happen if session bundle was created
3363 // properly by #StartAccountSession.
3364 if (TextUtils.isEmpty(accountType)) {
3365 sendErrorResponse(
3366 response,
3367 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3368 "accountType is empty");
3369 return;
3370 }
3371
3372 // If by any chances, decryptedBundle contains colliding keys with
3373 // system info
3374 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3375 // update credentials flow, we should replace with the new values of the current call.
3376 if (appInfo != null) {
3377 decryptedBundle.putAll(appInfo);
3378 }
3379
3380 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003381 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003382 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3383 } catch (GeneralSecurityException e) {
3384 if (Log.isLoggable(TAG, Log.DEBUG)) {
3385 Log.v(TAG, "Failed to decrypt session bundle!", e);
3386 }
3387 sendErrorResponse(
3388 response,
3389 AccountManager.ERROR_CODE_BAD_REQUEST,
3390 "failed to decrypt session bundle");
3391 return;
3392 }
3393
Sandra Kwan0b84b452016-01-20 15:25:42 -08003394 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003395 sendErrorResponse(
3396 response,
3397 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3398 "User cannot modify accounts of this type (policy).");
3399 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3400 userId);
3401 return;
3402 }
3403
3404 long identityToken = clearCallingIdentity();
3405 try {
3406 UserAccounts accounts = getUserAccounts(userId);
3407 logRecordWithUid(
3408 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003409 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3410 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003411 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003412 new Session(
3413 accounts,
3414 response,
3415 accountType,
3416 expectActivityLaunch,
3417 true /* stripAuthTokenFromResult */,
3418 null /* accountName */,
3419 false /* authDetailsRequired */,
3420 true /* updateLastAuthenticationTime */) {
3421 @Override
3422 public void run() throws RemoteException {
3423 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3424 }
3425
3426 @Override
3427 protected String toDebugString(long now) {
3428 return super.toDebugString(now)
3429 + ", finishSession"
3430 + ", accountType " + accountType;
3431 }
3432 }.bind();
3433 } finally {
3434 restoreCallingIdentity(identityToken);
3435 }
3436 }
3437
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003438 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003439 final DevicePolicyManagerInternal dpmi =
3440 LocalServices.getService(DevicePolicyManagerInternal.class);
3441 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003442 if (dpmi == null) {
3443 intent = getDefaultCantAddAccountIntent(errorCode);
3444 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003445 intent = dpmi.createUserRestrictionSupportIntent(userId,
3446 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3447 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3448 intent = dpmi.createShowAdminSupportIntent(userId, false);
3449 }
3450 if (intent == null) {
3451 intent = getDefaultCantAddAccountIntent(errorCode);
3452 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003453 long identityToken = clearCallingIdentity();
3454 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003455 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003456 } finally {
3457 restoreCallingIdentity(identityToken);
3458 }
3459 }
3460
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003461 /**
3462 * Called when we don't know precisely who is preventing us from adding an account.
3463 */
3464 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3465 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3466 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3467 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3468 return cantAddAccount;
3469 }
3470
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003471 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003472 public void confirmCredentialsAsUser(
3473 IAccountManagerResponse response,
3474 final Account account,
3475 final Bundle options,
3476 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003477 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003478 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003479 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3481 Log.v(TAG, "confirmCredentials: " + account
3482 + ", response " + response
3483 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003484 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003485 + ", pid " + Binder.getCallingPid());
3486 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003487 // Only allow the system process to read accounts of other users
3488 if (isCrossUser(callingUid, userId)) {
3489 throw new SecurityException(
3490 String.format(
3491 "User %s trying to confirm account credentials for %s" ,
3492 UserHandle.getCallingUserId(),
3493 userId));
3494 }
Fred Quintana382601f2010-03-25 12:25:10 -07003495 if (response == null) throw new IllegalArgumentException("response is null");
3496 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003497 long identityToken = clearCallingIdentity();
3498 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003499 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003500 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003501 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003502 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003503 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003504 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003505 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003506 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003507 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003508 protected String toDebugString(long now) {
3509 return super.toDebugString(now) + ", confirmCredentials"
3510 + ", " + account;
3511 }
3512 }.bind();
3513 } finally {
3514 restoreCallingIdentity(identityToken);
3515 }
Fred Quintana60307342009-03-24 22:48:12 -07003516 }
3517
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003518 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003519 public void updateCredentials(IAccountManagerResponse response, final Account account,
3520 final String authTokenType, final boolean expectActivityLaunch,
3521 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003522 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003523 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3524 Log.v(TAG, "updateCredentials: " + account
3525 + ", response " + response
3526 + ", authTokenType " + authTokenType
3527 + ", expectActivityLaunch " + expectActivityLaunch
3528 + ", caller's uid " + Binder.getCallingUid()
3529 + ", pid " + Binder.getCallingPid());
3530 }
Fred Quintana382601f2010-03-25 12:25:10 -07003531 if (response == null) throw new IllegalArgumentException("response is null");
3532 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003533 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003534 long identityToken = clearCallingIdentity();
3535 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003536 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003537 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003538 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003539 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003540 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003541 public void run() throws RemoteException {
3542 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3543 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003544 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003545 protected String toDebugString(long now) {
3546 if (loginOptions != null) loginOptions.keySet();
3547 return super.toDebugString(now) + ", updateCredentials"
3548 + ", " + account
3549 + ", authTokenType " + authTokenType
3550 + ", loginOptions " + loginOptions;
3551 }
3552 }.bind();
3553 } finally {
3554 restoreCallingIdentity(identityToken);
3555 }
Fred Quintana60307342009-03-24 22:48:12 -07003556 }
3557
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003558 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003559 public void startUpdateCredentialsSession(
3560 IAccountManagerResponse response,
3561 final Account account,
3562 final String authTokenType,
3563 final boolean expectActivityLaunch,
3564 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003565 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003566 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3567 Log.v(TAG,
3568 "startUpdateCredentialsSession: " + account + ", response " + response
3569 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3570 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3571 + ", pid " + Binder.getCallingPid());
3572 }
3573 if (response == null) {
3574 throw new IllegalArgumentException("response is null");
3575 }
3576 if (account == null) {
3577 throw new IllegalArgumentException("account is null");
3578 }
Sandra Kwana578d112015-12-16 16:01:43 -08003579
3580 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003581 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003582
3583 // Check to see if the Password should be included to the caller.
3584 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3585 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003586 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003587
Sandra Kwane68c37e2015-11-12 17:11:49 -08003588 long identityToken = clearCallingIdentity();
3589 try {
3590 UserAccounts accounts = getUserAccounts(userId);
3591 new StartAccountSession(
3592 accounts,
3593 response,
3594 account.type,
3595 expectActivityLaunch,
3596 account.name,
3597 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003598 true /* updateLastCredentialTime */,
3599 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003600 @Override
3601 public void run() throws RemoteException {
3602 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3603 loginOptions);
3604 }
3605
3606 @Override
3607 protected String toDebugString(long now) {
3608 if (loginOptions != null)
3609 loginOptions.keySet();
3610 return super.toDebugString(now)
3611 + ", startUpdateCredentialsSession"
3612 + ", " + account
3613 + ", authTokenType " + authTokenType
3614 + ", loginOptions " + loginOptions;
3615 }
3616 }.bind();
3617 } finally {
3618 restoreCallingIdentity(identityToken);
3619 }
3620 }
3621
3622 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003623 public void isCredentialsUpdateSuggested(
3624 IAccountManagerResponse response,
3625 final Account account,
3626 final String statusToken) {
3627 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3628 Log.v(TAG,
3629 "isCredentialsUpdateSuggested: " + account + ", response " + response
3630 + ", caller's uid " + Binder.getCallingUid()
3631 + ", pid " + Binder.getCallingPid());
3632 }
3633 if (response == null) {
3634 throw new IllegalArgumentException("response is null");
3635 }
3636 if (account == null) {
3637 throw new IllegalArgumentException("account is null");
3638 }
3639 if (TextUtils.isEmpty(statusToken)) {
3640 throw new IllegalArgumentException("status token is empty");
3641 }
3642
Sandra Kwan390c9d22016-01-12 14:13:37 -08003643 int usrId = UserHandle.getCallingUserId();
3644 long identityToken = clearCallingIdentity();
3645 try {
3646 UserAccounts accounts = getUserAccounts(usrId);
3647 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3648 false /* stripAuthTokenFromResult */, account.name,
3649 false /* authDetailsRequired */) {
3650 @Override
3651 protected String toDebugString(long now) {
3652 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3653 + ", " + account;
3654 }
3655
3656 @Override
3657 public void run() throws RemoteException {
3658 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3659 }
3660
3661 @Override
3662 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003663 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003664 IAccountManagerResponse response = getResponseAndClose();
3665 if (response == null) {
3666 return;
3667 }
3668
3669 if (result == null) {
3670 sendErrorResponse(
3671 response,
3672 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3673 "null bundle");
3674 return;
3675 }
3676
3677 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3678 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3679 + response);
3680 }
3681 // Check to see if an error occurred. We know if an error occurred because all
3682 // error codes are greater than 0.
3683 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3684 sendErrorResponse(response,
3685 result.getInt(AccountManager.KEY_ERROR_CODE),
3686 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3687 return;
3688 }
3689 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3690 sendErrorResponse(
3691 response,
3692 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3693 "no result in response");
3694 return;
3695 }
3696 final Bundle newResult = new Bundle();
3697 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3698 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3699 sendResponse(response, newResult);
3700 }
3701 }.bind();
3702 } finally {
3703 restoreCallingIdentity(identityToken);
3704 }
3705 }
3706
3707 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003708 public void editProperties(IAccountManagerResponse response, final String accountType,
3709 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003710 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003711 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3712 Log.v(TAG, "editProperties: accountType " + accountType
3713 + ", response " + response
3714 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003715 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003716 + ", pid " + Binder.getCallingPid());
3717 }
Fred Quintana382601f2010-03-25 12:25:10 -07003718 if (response == null) throw new IllegalArgumentException("response is null");
3719 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003720 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003721 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3722 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003723 String msg = String.format(
3724 "uid %s cannot edit authenticator properites for account type: %s",
3725 callingUid,
3726 accountType);
3727 throw new SecurityException(msg);
3728 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003729 long identityToken = clearCallingIdentity();
3730 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003731 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003732 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003733 true /* stripAuthTokenFromResult */, null /* accountName */,
3734 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003735 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003736 public void run() throws RemoteException {
3737 mAuthenticator.editProperties(this, mAccountType);
3738 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003739 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003740 protected String toDebugString(long now) {
3741 return super.toDebugString(now) + ", editProperties"
3742 + ", accountType " + accountType;
3743 }
3744 }.bind();
3745 } finally {
3746 restoreCallingIdentity(identityToken);
3747 }
Fred Quintana60307342009-03-24 22:48:12 -07003748 }
3749
Amith Yamasani12747872015-12-07 14:19:49 -08003750 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003751 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3752 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003753 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003754 throw new SecurityException("Can be called only by system UID");
3755 }
3756 Preconditions.checkNotNull(account, "account cannot be null");
3757 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3758 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3759
3760 final int userId = userHandle.getIdentifier();
3761
3762 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3763
3764 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003765 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003766 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003767 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003768 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003769 return false;
3770 }
3771 }
3772
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003773 // Returns package with oldest target SDK for given UID.
3774 private String getPackageNameForUid(int uid) {
3775 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3776 if (ArrayUtils.isEmpty(packageNames)) {
3777 return null;
3778 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003779 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003780 if (packageNames.length == 1) {
3781 return packageName;
3782 }
3783 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003784 int oldestVersion = Integer.MAX_VALUE;
3785 for (String name : packageNames) {
3786 try {
3787 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3788 if (applicationInfo != null) {
3789 int version = applicationInfo.targetSdkVersion;
3790 if (version < oldestVersion) {
3791 oldestVersion = version;
3792 packageName = name;
3793 }
3794 }
3795 } catch (NameNotFoundException e) {
3796 // skip
3797 }
3798 }
3799 return packageName;
3800 }
3801
Svet Ganovf6d424f12016-09-20 20:18:53 -07003802 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3803 int uid) {
3804 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003805 packageName = getPackageNameForUid(uid);
3806 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003807 return false;
3808 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003809 }
3810
3811 // Use null token which means any token. Having a token means the package
3812 // is trusted by the authenticator, hence it is fine to access the account.
3813 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3814 return true;
3815 }
3816 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003817 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003818
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003819 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003820 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003821 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003822 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003823 }
3824
3825 @Override
3826 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3827 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003828 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003829 throw new SecurityException("Can be called only by system UID");
3830 }
3831
3832 Preconditions.checkNotNull(account, "account cannot be null");
3833 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3834 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3835
3836 final int userId = userHandle.getIdentifier();
3837
3838 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3839
3840 final int uid;
3841 try {
3842 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3843 } catch (NameNotFoundException e) {
3844 Slog.e(TAG, "Unknown package " + packageName);
3845 return null;
3846 }
3847
3848 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
3849
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003850 final long identity = Binder.clearCallingIdentity();
3851 try {
3852 return PendingIntent.getActivityAsUser(
3853 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
3854 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
3855 null, new UserHandle(userId)).getIntentSender();
3856 } finally {
3857 Binder.restoreCallingIdentity(identity);
3858 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003859 }
3860
3861 private Intent newRequestAccountAccessIntent(Account account, String packageName,
3862 int uid, RemoteCallback callback) {
3863 return newGrantCredentialsPermissionIntent(account, packageName, uid,
3864 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
3865 @Override
3866 public void onResult(Bundle value) throws RemoteException {
3867 handleAuthenticatorResponse(true);
3868 }
3869
3870 @Override
3871 public void onRequestContinued() {
3872 /* ignore */
3873 }
3874
3875 @Override
3876 public void onError(int errorCode, String errorMessage) throws RemoteException {
3877 handleAuthenticatorResponse(false);
3878 }
3879
3880 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
3881 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07003882 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003883 UserHandle.getUserHandleForUid(uid));
3884 if (callback != null) {
3885 Bundle result = new Bundle();
3886 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
3887 callback.sendResult(result);
3888 }
3889 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003890 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003891 }
3892
3893 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003894 public boolean someUserHasAccount(@NonNull final Account account) {
3895 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3896 throw new SecurityException("Only system can check for accounts across users");
3897 }
3898 final long token = Binder.clearCallingIdentity();
3899 try {
3900 AccountAndUser[] allAccounts = getAllAccounts();
3901 for (int i = allAccounts.length - 1; i >= 0; i--) {
3902 if (allAccounts[i].account.equals(account)) {
3903 return true;
3904 }
3905 }
3906 return false;
3907 } finally {
3908 Binder.restoreCallingIdentity(token);
3909 }
3910 }
3911
Fred Quintana33269202009-04-20 16:05:10 -07003912 private class GetAccountsByTypeAndFeatureSession extends Session {
3913 private final String[] mFeatures;
3914 private volatile Account[] mAccountsOfType = null;
3915 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3916 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003917 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003918 private final String mPackageName;
Fred Quintana33269202009-04-20 16:05:10 -07003919
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003920 public GetAccountsByTypeAndFeatureSession(
3921 UserAccounts accounts,
3922 IAccountManagerResponse response,
3923 String type,
3924 String[] features,
3925 int callingUid,
3926 String packageName) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003927 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003928 true /* stripAuthTokenFromResult */, null /* accountName */,
3929 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003930 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003931 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003932 mPackageName = packageName;
Fred Quintana33269202009-04-20 16:05:10 -07003933 }
3934
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003935 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003936 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07003937 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
3938 mCallingUid, mPackageName, false /* include managed not visible*/);
Fred Quintana33269202009-04-20 16:05:10 -07003939 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07003940 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07003941 mCurrentAccount = 0;
3942
3943 checkAccount();
3944 }
3945
3946 public void checkAccount() {
3947 if (mCurrentAccount >= mAccountsOfType.length) {
3948 sendResult();
3949 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003950 }
Fred Quintana33269202009-04-20 16:05:10 -07003951
Fred Quintana29e94b82010-03-10 12:11:51 -08003952 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3953 if (accountAuthenticator == null) {
3954 // It is possible that the authenticator has died, which is indicated by
3955 // mAuthenticator being set to null. If this happens then just abort.
3956 // There is no need to send back a result or error in this case since
3957 // that already happened when mAuthenticator was cleared.
3958 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3959 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3960 + " connected to the authenticator, " + toDebugString());
3961 }
3962 return;
3963 }
Fred Quintana33269202009-04-20 16:05:10 -07003964 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003965 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003966 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003967 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003968 }
3969 }
3970
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003971 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003972 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003973 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003974 mNumResults++;
3975 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003976 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003977 return;
3978 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003979 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003980 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3981 }
3982 mCurrentAccount++;
3983 checkAccount();
3984 }
3985
3986 public void sendResult() {
3987 IAccountManagerResponse response = getResponseAndClose();
3988 if (response != null) {
3989 try {
3990 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3991 for (int i = 0; i < accounts.length; i++) {
3992 accounts[i] = mAccountsWithFeatures.get(i);
3993 }
Fred Quintana56285a62010-12-02 14:20:51 -08003994 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3995 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3996 + response);
3997 }
Fred Quintana33269202009-04-20 16:05:10 -07003998 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003999 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004000 response.onResult(result);
4001 } catch (RemoteException e) {
4002 // if the caller is dead then there is no one to care about remote exceptions
4003 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4004 Log.v(TAG, "failure while notifying response", e);
4005 }
4006 }
4007 }
4008 }
4009
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004010 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004011 protected String toDebugString(long now) {
4012 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4013 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4014 }
4015 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004016
Amith Yamasani04e0d262012-02-14 11:50:53 -08004017 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004018 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004019 * @hide
4020 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004021 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004022 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004023 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004024 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004025 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4026 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004027 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004028 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004029 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004030 long identityToken = clearCallingIdentity();
4031 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004032 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004033 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004034 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004035 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004036 opPackageName,
4037 visibleAccountTypes,
4038 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004039 } finally {
4040 restoreCallingIdentity(identityToken);
4041 }
4042 }
4043
Amith Yamasanif29f2362012-04-05 18:29:52 -07004044 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004045 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004046 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004047 * @hide
4048 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004049 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004050 public AccountAndUser[] getRunningAccounts() {
4051 final int[] runningUserIds;
4052 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004053 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004054 } catch (RemoteException e) {
4055 // Running in system_server; should never happen
4056 throw new RuntimeException(e);
4057 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004058 return getAccounts(runningUserIds);
4059 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004060
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004061 /**
4062 * Returns accounts for all users, ignores visibility values.
4063 *
4064 * @hide
4065 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004066 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004067 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004068 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004069 final int[] userIds = new int[users.size()];
4070 for (int i = 0; i < userIds.length; i++) {
4071 userIds[i] = users.get(i).id;
4072 }
4073 return getAccounts(userIds);
4074 }
4075
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004076 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004077 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004078 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004079 for (int userId : userIds) {
4080 UserAccounts userAccounts = getUserAccounts(userId);
4081 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004082 Account[] accounts = getAccountsFromCache(
4083 userAccounts,
4084 null /* type */,
4085 Binder.getCallingUid(),
4086 null /* packageName */,
4087 false /* include managed not visible*/);
4088 for (Account account : accounts) {
4089 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004090 }
4091 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004092
4093 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4094 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004095 }
4096
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004097 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004098 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004099 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004100 int callingUid = Binder.getCallingUid();
4101 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004102 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004103 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004104 }
4105
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004106 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004107 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004108 String type,
4109 int userId,
4110 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004111 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004112 String opPackageName,
4113 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004114 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004115 // Only allow the system process to read accounts of other users
4116 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004117 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004118 && mContext.checkCallingOrSelfPermission(
4119 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4120 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004121 throw new SecurityException("User " + UserHandle.getCallingUserId()
4122 + " trying to get account for " + userId);
4123 }
4124
Fred Quintana56285a62010-12-02 14:20:51 -08004125 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4126 Log.v(TAG, "getAccounts: accountType " + type
4127 + ", caller's uid " + Binder.getCallingUid()
4128 + ", pid " + Binder.getCallingPid());
4129 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004130
4131 // If the original calling app was using account choosing activity
4132 // provided by the framework or authenticator we'll passing in
4133 // the original caller's uid here, which is what should be used for filtering.
4134 List<String> managedTypes =
4135 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4136 if (packageUid != -1 &&
4137 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4138 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004139 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004140 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004141 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004142 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4143 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004144 if (visibleAccountTypes.isEmpty()
4145 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004146 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004147 } else if (visibleAccountTypes.contains(type)) {
4148 // Prune the list down to just the requested type.
4149 visibleAccountTypes = new ArrayList<>();
4150 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004151 } // else aggregate all the visible accounts (it won't matter if the
4152 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004153
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004154 long identityToken = clearCallingIdentity();
4155 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004156 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004157 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004158 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004159 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004160 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004161 visibleAccountTypes,
4162 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004163 } finally {
4164 restoreCallingIdentity(identityToken);
4165 }
4166 }
4167
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004168 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004169 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004170 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004171 int callingUid,
4172 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004173 List<String> visibleAccountTypes,
4174 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004175 ArrayList<Account> visibleAccounts = new ArrayList<>();
4176 for (String visibleType : visibleAccountTypes) {
4177 Account[] accountsForType = getAccountsFromCache(
4178 userAccounts, visibleType, callingUid, callingPackage,
4179 includeUserManagedNotVisible);
4180 if (accountsForType != null) {
4181 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004182 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004183 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004184 Account[] result = new Account[visibleAccounts.size()];
4185 for (int i = 0; i < visibleAccounts.size(); i++) {
4186 result[i] = visibleAccounts.get(i);
4187 }
4188 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004189 }
4190
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004191 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004192 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4193 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004194 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004195 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004196 for (Account account : accounts) {
4197 addSharedAccountAsUser(account, userId);
4198 }
4199 }
4200
4201 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004202 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004203 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004204 accounts.accountsDb.deleteSharedAccount(account);
4205 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004206 if (accountId < 0) {
4207 Log.w(TAG, "insertAccountIntoDatabase: " + account
4208 + ", skipping the DB insert failed");
4209 return false;
4210 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004211 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4212 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004213 return true;
4214 }
4215
4216 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004217 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4218 userId = handleIncomingUser(userId);
4219 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004220 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4221 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004222 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004223 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004224 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004225 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004226 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004227 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004228 }
4229 return r > 0;
4230 }
4231
4232 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004233 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004234 return removeSharedAccountAsUser(account, userId, getCallingUid());
4235 }
4236
4237 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004238 userId = handleIncomingUser(userId);
4239 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004240 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4241 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004242 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004243 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004244 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004245 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004246 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004247 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004248 }
4249
4250 @Override
4251 public Account[] getSharedAccountsAsUser(int userId) {
4252 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004253 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004254 synchronized (accounts.dbLock) {
4255 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4256 Account[] accountArray = new Account[accountList.size()];
4257 accountList.toArray(accountArray);
4258 return accountArray;
4259 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004260 }
4261
4262 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004263 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004264 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004265 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004266 }
4267
Amith Yamasani27db4682013-03-30 17:07:47 -07004268 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004269 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004270 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004271 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004272 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004273 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004274 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4275 + callingUid + " with uid=" + uid);
4276 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004277 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004278 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004279 }
4280
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004281 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004282 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004283 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4284 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004285 int callingUid = Binder.getCallingUid();
4286 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004287 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004288 int packageUid = -1;
4289 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004290 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4291 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004292 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004293 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004294 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004295 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004296 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4297 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004298 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004299 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004300 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004301 }
4302
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004303 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004304 public void getAccountsByFeatures(
4305 IAccountManagerResponse response,
4306 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004307 String[] features,
4308 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004309 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004310 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4312 Log.v(TAG, "getAccounts: accountType " + type
4313 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004314 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004315 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004316 + ", pid " + Binder.getCallingPid());
4317 }
Fred Quintana382601f2010-03-25 12:25:10 -07004318 if (response == null) throw new IllegalArgumentException("response is null");
4319 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004320 int userId = UserHandle.getCallingUserId();
4321
Svetoslavf3f02ac2015-09-08 14:36:35 -07004322 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4323 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004324 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004325 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004326 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004327 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004328 try {
4329 response.onResult(result);
4330 } catch (RemoteException e) {
4331 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4332 }
4333 return;
4334 }
Fred Quintana33269202009-04-20 16:05:10 -07004335 long identityToken = clearCallingIdentity();
4336 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004337 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004338 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004339 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4340 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004341 Bundle result = new Bundle();
4342 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4343 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004344 return;
4345 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004346 new GetAccountsByTypeAndFeatureSession(
4347 userAccounts,
4348 response,
4349 type,
4350 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004351 callingUid,
4352 opPackageName).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004353 } finally {
4354 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004355 }
4356 }
4357
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004358 @Override
4359 public void onAccountAccessed(String token) throws RemoteException {
4360 final int uid = Binder.getCallingUid();
4361 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4362 return;
4363 }
4364 final int userId = UserHandle.getCallingUserId();
4365 final long identity = Binder.clearCallingIdentity();
4366 try {
4367 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4368 if (Objects.equals(account.getAccessId(), token)) {
4369 // An app just accessed the account. At this point it knows about
4370 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004371 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004372 if (!hasAccountAccess(account, null, uid)) {
4373 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4374 uid, true);
4375 }
4376 }
4377 }
4378 } finally {
4379 Binder.restoreCallingIdentity(identity);
4380 }
4381 }
4382
Fred Quintanaa698f422009-04-08 19:14:54 -07004383 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004384 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004385 IAccountManagerResponse mResponse;
4386 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004387 final boolean mExpectActivityLaunch;
4388 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004389 final String mAccountName;
4390 // Indicates if we need to add auth details(like last credential time)
4391 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004392 // If set, we need to update the last authenticated time. This is
4393 // currently
4394 // used on
4395 // successful confirming credentials.
4396 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004397
Fred Quintana33269202009-04-20 16:05:10 -07004398 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004399 private int mNumRequestContinued = 0;
4400 private int mNumErrors = 0;
4401
Fred Quintana60307342009-03-24 22:48:12 -07004402 IAccountAuthenticator mAuthenticator = null;
4403
Fred Quintana8570f742010-02-18 10:32:54 -08004404 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004405 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004406
Amith Yamasani04e0d262012-02-14 11:50:53 -08004407 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004408 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4409 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004410 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4411 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4412 }
4413
4414 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4415 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4416 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004417 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004418 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004419 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004420 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004421 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004422 mResponse = response;
4423 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004424 mExpectActivityLaunch = expectActivityLaunch;
4425 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004426 mAccountName = accountName;
4427 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004428 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004429
Fred Quintanaa698f422009-04-08 19:14:54 -07004430 synchronized (mSessions) {
4431 mSessions.put(toString(), this);
4432 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004433 if (response != null) {
4434 try {
4435 response.asBinder().linkToDeath(this, 0 /* flags */);
4436 } catch (RemoteException e) {
4437 mResponse = null;
4438 binderDied();
4439 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004440 }
Fred Quintana60307342009-03-24 22:48:12 -07004441 }
4442
Fred Quintanaa698f422009-04-08 19:14:54 -07004443 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004444 if (mResponse == null) {
4445 // this session has already been closed
4446 return null;
4447 }
Fred Quintana60307342009-03-24 22:48:12 -07004448 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004449 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004450 return response;
4451 }
4452
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004453 /**
4454 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4455 * security policy.
4456 *
4457 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004458 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004459 * supplied entries in the system Settings app.
4460 */
4461 protected void checkKeyIntent(
4462 int authUid,
4463 Intent intent) throws SecurityException {
4464 long bid = Binder.clearCallingIdentity();
4465 try {
4466 PackageManager pm = mContext.getPackageManager();
4467 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4468 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4469 int targetUid = targetActivityInfo.applicationInfo.uid;
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004470 if (!isExportedSystemActivity(targetActivityInfo)
4471 && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4472 targetUid))) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004473 String pkgName = targetActivityInfo.packageName;
4474 String activityName = targetActivityInfo.name;
4475 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4476 + "does not share a signature with the supplying authenticator (%s).";
4477 throw new SecurityException(
4478 String.format(tmpl, activityName, pkgName, mAccountType));
4479 }
4480 } finally {
4481 Binder.restoreCallingIdentity(bid);
4482 }
4483 }
4484
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004485 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4486 String className = activityInfo.name;
4487 return "android".equals(activityInfo.packageName) &&
4488 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4489 || CantAddAccountActivity.class.getName().equals(className));
4490 }
4491
Fred Quintanaa698f422009-04-08 19:14:54 -07004492 private void close() {
4493 synchronized (mSessions) {
4494 if (mSessions.remove(toString()) == null) {
4495 // the session was already closed, so bail out now
4496 return;
4497 }
4498 }
4499 if (mResponse != null) {
4500 // stop listening for response deaths
4501 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4502
4503 // clear this so that we don't accidentally send any further results
4504 mResponse = null;
4505 }
4506 cancelTimeout();
4507 unbind();
4508 }
4509
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004510 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004511 public void binderDied() {
4512 mResponse = null;
4513 close();
4514 }
4515
4516 protected String toDebugString() {
4517 return toDebugString(SystemClock.elapsedRealtime());
4518 }
4519
4520 protected String toDebugString(long now) {
4521 return "Session: expectLaunch " + mExpectActivityLaunch
4522 + ", connected " + (mAuthenticator != null)
4523 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4524 + "/" + mNumErrors + ")"
4525 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4526 }
4527
Fred Quintana60307342009-03-24 22:48:12 -07004528 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004529 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4530 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4531 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004532 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004533 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004534 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004535 }
4536 }
4537
4538 private void unbind() {
4539 if (mAuthenticator != null) {
4540 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004541 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004542 }
4543 }
4544
Fred Quintana60307342009-03-24 22:48:12 -07004545 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004546 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004547 }
4548
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004549 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004550 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004551 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004552 try {
4553 run();
4554 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004555 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004556 "remote exception");
4557 }
Fred Quintana60307342009-03-24 22:48:12 -07004558 }
4559
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004560 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004561 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004562 mAuthenticator = null;
4563 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004564 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004565 try {
4566 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4567 "disconnected");
4568 } catch (RemoteException e) {
4569 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4570 Log.v(TAG, "Session.onServiceDisconnected: "
4571 + "caught RemoteException while responding", e);
4572 }
4573 }
Fred Quintana60307342009-03-24 22:48:12 -07004574 }
4575 }
4576
Fred Quintanab839afc2009-10-14 15:57:28 -07004577 public abstract void run() throws RemoteException;
4578
Fred Quintana60307342009-03-24 22:48:12 -07004579 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004580 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004581 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004582 try {
4583 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4584 "timeout");
4585 } catch (RemoteException e) {
4586 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4587 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4588 e);
4589 }
4590 }
Fred Quintana60307342009-03-24 22:48:12 -07004591 }
4592 }
4593
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004594 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004595 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004596 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004597 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004598 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004599 if (result != null) {
4600 boolean isSuccessfulConfirmCreds = result.getBoolean(
4601 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004602 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004603 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4604 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004605 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004606 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4607 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004608 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004609 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004610 if (needUpdate || mAuthDetailsRequired) {
4611 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4612 if (needUpdate && accountPresent) {
4613 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4614 }
4615 if (mAuthDetailsRequired) {
4616 long lastAuthenticatedTime = -1;
4617 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004618 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004619 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004620 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004621 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004622 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004623 lastAuthenticatedTime);
4624 }
4625 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004626 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004627 if (result != null
4628 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004629 checkKeyIntent(
4630 Binder.getCallingUid(),
4631 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004632 }
4633 if (result != null
4634 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004635 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4636 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004637 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4638 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004639 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4640 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004641 }
Fred Quintana60307342009-03-24 22:48:12 -07004642 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004643 IAccountManagerResponse response;
4644 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004645 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004646 response = mResponse;
4647 } else {
4648 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004649 }
Fred Quintana60307342009-03-24 22:48:12 -07004650 if (response != null) {
4651 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004652 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004653 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4654 Log.v(TAG, getClass().getSimpleName()
4655 + " calling onError() on response " + response);
4656 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004657 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004658 "null bundle returned");
4659 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004660 if (mStripAuthTokenFromResult) {
4661 result.remove(AccountManager.KEY_AUTHTOKEN);
4662 }
Fred Quintana56285a62010-12-02 14:20:51 -08004663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4664 Log.v(TAG, getClass().getSimpleName()
4665 + " calling onResult() on response " + response);
4666 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004667 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4668 (intent == null)) {
4669 // All AccountManager error codes are greater than 0
4670 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4671 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4672 } else {
4673 response.onResult(result);
4674 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004675 }
Fred Quintana60307342009-03-24 22:48:12 -07004676 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004677 // if the caller is dead then there is no one to care about remote exceptions
4678 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4679 Log.v(TAG, "failure while notifying response", e);
4680 }
Fred Quintana60307342009-03-24 22:48:12 -07004681 }
4682 }
4683 }
Fred Quintana60307342009-03-24 22:48:12 -07004684
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004685 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004686 public void onRequestContinued() {
4687 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004688 }
4689
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004690 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004691 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004692 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004693 IAccountManagerResponse response = getResponseAndClose();
4694 if (response != null) {
4695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004696 Log.v(TAG, getClass().getSimpleName()
4697 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004698 }
4699 try {
4700 response.onError(errorCode, errorMessage);
4701 } catch (RemoteException e) {
4702 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4703 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4704 }
4705 }
4706 } else {
4707 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4708 Log.v(TAG, "Session.onError: already closed");
4709 }
Fred Quintana60307342009-03-24 22:48:12 -07004710 }
4711 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004712
4713 /**
4714 * find the component name for the authenticator and initiate a bind
4715 * if no authenticator or the bind fails then return false, otherwise return true
4716 */
4717 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004718 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4719 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4720 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004721 if (authenticatorInfo == null) {
4722 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4723 Log.v(TAG, "there is no authenticator for " + authenticatorType
4724 + ", bailing out");
4725 }
4726 return false;
4727 }
4728
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004729 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004730 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004731 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4732 + " which isn't encryption aware");
4733 return false;
4734 }
4735
Fred Quintanab839afc2009-10-14 15:57:28 -07004736 Intent intent = new Intent();
4737 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4738 intent.setComponent(authenticatorInfo.componentName);
4739 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4740 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4741 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004742 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004743 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004744 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4745 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4746 }
4747 return false;
4748 }
4749
Fred Quintanab839afc2009-10-14 15:57:28 -07004750 return true;
4751 }
Fred Quintana60307342009-03-24 22:48:12 -07004752 }
4753
Svet Ganov5d09c992016-09-07 09:57:41 -07004754 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07004755 MessageHandler(Looper looper) {
4756 super(looper);
4757 }
Costin Manolache3348f142009-09-29 18:58:36 -07004758
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004759 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004760 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004761 switch (msg.what) {
4762 case MESSAGE_TIMED_OUT:
4763 Session session = (Session)msg.obj;
4764 session.onTimedOut();
4765 break;
4766
Amith Yamasani5be347b2013-03-31 17:44:31 -07004767 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004768 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004769 break;
4770
Fred Quintana60307342009-03-24 22:48:12 -07004771 default:
4772 throw new IllegalStateException("unhandled message: " + msg.what);
4773 }
4774 }
4775 }
4776
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004777 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004778 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004779 }
4780
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004781 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004782 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004783 }
4784
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004785 /*
4786 * This function receives an opened writable database.
4787 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004788 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004789 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004790 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004791 }
4792
4793 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004794 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004795 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004796 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004797 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004798
4799 class LogRecordTask implements Runnable {
4800 private final String action;
4801 private final String tableName;
4802 private final long accountId;
4803 private final UserAccounts userAccount;
4804 private final int callingUid;
4805 private final long userDebugDbInsertionPoint;
4806
4807 LogRecordTask(final String action,
4808 final String tableName,
4809 final long accountId,
4810 final UserAccounts userAccount,
4811 final int callingUid,
4812 final long userDebugDbInsertionPoint) {
4813 this.action = action;
4814 this.tableName = tableName;
4815 this.accountId = accountId;
4816 this.userAccount = userAccount;
4817 this.callingUid = callingUid;
4818 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
4819 }
4820
4821 public void run() {
4822 SQLiteStatement logStatement = userAccount.statementForLogging;
4823 logStatement.bindLong(1, accountId);
4824 logStatement.bindString(2, action);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004825 logStatement.bindString(3, mDateFormat.format(new Date()));
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004826 logStatement.bindLong(4, callingUid);
4827 logStatement.bindString(5, tableName);
4828 logStatement.bindLong(6, userDebugDbInsertionPoint);
4829 logStatement.execute();
4830 logStatement.clearBindings();
4831 }
4832 }
4833
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004834 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
4835 callingUid, userAccount.debugDbInsertionPoint);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004836 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004837 % AccountsDb.MAX_DEBUG_DB_SIZE;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004838 mHandler.post(logTask);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004839 }
4840
4841 /*
4842 * This should only be called once to compile the sql statement for logging
4843 * and to find the insertion point.
4844 */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004845 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(UserAccounts userAccount) {
4846 userAccount.debugDbInsertionPoint = userAccount.accountsDb
4847 .calculateDebugTableInsertionPoint();
4848 userAccount.statementForLogging = userAccount.accountsDb.compileSqlStatementForLogging();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004849 }
4850
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004851 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004852 return asBinder();
4853 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004854
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004855 /**
4856 * Searches array of arguments for the specified string
4857 * @param args array of argument strings
4858 * @param value value to search for
4859 * @return true if the value is contained in the array
4860 */
4861 private static boolean scanArgs(String[] args, String value) {
4862 if (args != null) {
4863 for (String arg : args) {
4864 if (value.equals(arg)) {
4865 return true;
4866 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004867 }
4868 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004869 return false;
4870 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004871
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004872 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004873 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004874 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4875 != PackageManager.PERMISSION_GRANTED) {
4876 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4877 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4878 + " without permission " + android.Manifest.permission.DUMP);
4879 return;
4880 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004881 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004882 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004883
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004884 final List<UserInfo> users = getUserManager().getUsers();
4885 for (UserInfo user : users) {
4886 ipw.println("User " + user + ":");
4887 ipw.increaseIndent();
4888 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4889 ipw.println();
4890 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004891 }
4892 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004893
Amith Yamasani04e0d262012-02-14 11:50:53 -08004894 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4895 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004896 if (isCheckinRequest) {
4897 // This is a checkin request. *Only* upload the account types and the count of
4898 // each.
4899 synchronized (userAccounts.dbLock) {
4900 userAccounts.accountsDb.dumpDeAccountsTable(fout);
4901 }
4902 } else {
4903 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
4904 Process.SYSTEM_UID, null /* packageName */, false);
4905 fout.println("Accounts: " + accounts.length);
4906 for (Account account : accounts) {
4907 fout.println(" " + account);
4908 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004909
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004910 // Add debug information.
4911 fout.println();
4912 synchronized (userAccounts.dbLock) {
4913 userAccounts.accountsDb.dumpDebugTable(fout);
4914 }
4915 fout.println();
4916 synchronized (mSessions) {
4917 final long now = SystemClock.elapsedRealtime();
4918 fout.println("Active Sessions: " + mSessions.size());
4919 for (Session session : mSessions.values()) {
4920 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07004921 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004922 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004923
4924 fout.println();
4925 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004926 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004927 }
4928
Amith Yamasani04e0d262012-02-14 11:50:53 -08004929 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004930 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004931 long identityToken = clearCallingIdentity();
4932 try {
4933 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4934 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4935 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004936
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004937 if (intent.getComponent() != null &&
4938 GrantCredentialsPermissionActivity.class.getName().equals(
4939 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004940 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004941 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004942 Context contextForUser = getContextForUser(new UserHandle(userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004943 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004944 intent.addCategory(String.valueOf(notificationId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004945
Fred Quintana33f889a2009-09-14 17:31:26 -07004946 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004947 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05004948 Notification n =
4949 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004950 .setWhen(0)
4951 .setSmallIcon(android.R.drawable.stat_sys_warning)
4952 .setColor(contextForUser.getColor(
4953 com.android.internal.R.color.system_notification_accent_color))
4954 .setContentTitle(String.format(notificationTitleFormat, account.name))
4955 .setContentText(message)
4956 .setContentIntent(PendingIntent.getActivityAsUser(
4957 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004958 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004959 .build();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004960 installNotification(notificationId, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004961 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004962 } finally {
4963 restoreCallingIdentity(identityToken);
4964 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004965 }
4966
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004967 private void installNotification(int notificationId, final Notification notification,
4968 String packageName, int userId) {
4969 final long token = clearCallingIdentity();
4970 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07004971 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004972 try {
4973 notificationManager.enqueueNotificationWithTag(packageName, packageName, null,
4974 notificationId, notification, new int[1], userId);
4975 } catch (RemoteException e) {
4976 /* ignore - local call */
4977 }
4978 } finally {
4979 Binder.restoreCallingIdentity(token);
4980 }
Fred Quintana56285a62010-12-02 14:20:51 -08004981 }
4982
Fyodor Kupolovda993802016-09-21 14:47:10 -07004983 private void cancelNotification(int id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004984 cancelNotification(id, mContext.getPackageName(), user);
4985 }
4986
Fyodor Kupolovda993802016-09-21 14:47:10 -07004987 private void cancelNotification(int id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004988 long identityToken = clearCallingIdentity();
4989 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07004990 INotificationManager service = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004991 service.cancelNotificationWithTag(packageName, null, id, user.getIdentifier());
4992 } catch (RemoteException e) {
4993 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004994 } finally {
4995 restoreCallingIdentity(identityToken);
4996 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004997 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004998
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004999 private boolean isPermittedForPackage(String packageName, int userId, String... permissions) {
5000 final long identity = Binder.clearCallingIdentity();
5001 try {
5002 IPackageManager pm = ActivityThread.getPackageManager();
5003 for (String perm : permissions) {
5004 if (pm.checkPermission(perm, packageName, userId)
5005 == PackageManager.PERMISSION_GRANTED) {
5006 return true;
5007 }
5008 }
5009 } catch (RemoteException e) {
5010 /* ignore - local call */
5011 } finally {
5012 Binder.restoreCallingIdentity(identity);
5013 }
5014 return false;
5015 }
5016
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005017 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5018 for (String perm : permissions) {
5019 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5020 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5021 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5022 }
5023 final int opCode = AppOpsManager.permissionToOpCode(perm);
5024 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5025 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5026 return true;
5027 }
5028 }
5029 }
5030 return false;
5031 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005032
Amith Yamasani67df64b2012-12-14 12:09:36 -08005033 private int handleIncomingUser(int userId) {
5034 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005035 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005036 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5037 } catch (RemoteException re) {
5038 // Shouldn't happen, local.
5039 }
5040 return userId;
5041 }
5042
Christopher Tateccbf84f2013-05-08 15:25:41 -07005043 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005044 String[] packages;
5045 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005046 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005047 packages = mPackageManager.getPackagesForUid(callingUid);
5048 } finally {
5049 Binder.restoreCallingIdentity(identityToken);
5050 }
5051 if (packages == null) {
5052 Log.d(TAG, "No packages for callingUid " + callingUid);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005053 return false;
5054 }
Fred Quintana7be59642009-08-24 18:29:25 -07005055 for (String name : packages) {
5056 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005057 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005058 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005059 && (packageInfo.applicationInfo.privateFlags
5060 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005061 return true;
5062 }
5063 } catch (PackageManager.NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005064 Log.d(TAG, "Package not found " + e.getMessage());
Fred Quintana7be59642009-08-24 18:29:25 -07005065 return false;
5066 }
5067 }
5068 return false;
5069 }
5070
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005071 private boolean permissionIsGranted(
5072 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005073 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5075 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5076 }
5077 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005078 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005079
5080 if (isPrivileged(callerUid)) {
5081 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5082 Log.v(TAG, "Access to " + account + " granted calling uid "
5083 + callerUid + " privileged");
5084 }
5085 return true;
5086 }
5087 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5088 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5089 Log.v(TAG, "Access to " + account + " granted calling uid "
5090 + callerUid + " manages the account");
5091 }
5092 return true;
5093 }
5094 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5095 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5096 Log.v(TAG, "Access to " + account + " granted calling uid "
5097 + callerUid + " user granted access");
5098 }
5099 return true;
5100 }
5101
5102 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5103 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5104 }
5105
5106 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005107 }
5108
Svetoslavf3f02ac2015-09-08 14:36:35 -07005109 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5110 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005111 if (accountType == null) {
5112 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005113 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005114 return getTypesVisibleToCaller(callingUid, userId,
5115 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005116 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005117 }
5118
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005119 // Method checks visibility for applications targeing API level below {@link
5120 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005121 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005122 private boolean checkGetAccountsPermission(String packageName, int userId) {
5123 return isPermittedForPackage(packageName, userId, Manifest.permission.GET_ACCOUNTS,
5124 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5125 }
5126
5127 private boolean checkReadContactsPermission(String packageName, int userId) {
5128 return isPermittedForPackage(packageName, userId, Manifest.permission.READ_CONTACTS);
5129 }
5130
5131 /**
5132 * Method checks package uid and signature with Authenticator which manages accountType.
5133 *
5134 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5135 * SIGNATURE_CHECK_MISMATCH otherwise.
5136 */
5137 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5138 if (accountType == null) {
5139 return SIGNATURE_CHECK_MISMATCH;
5140 }
5141
5142 long identityToken = Binder.clearCallingIdentity();
5143 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5144 try {
5145 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5146 } finally {
5147 Binder.restoreCallingIdentity(identityToken);
5148 }
5149 // Check for signature match with Authenticator.
5150 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5151 : serviceInfos) {
5152 if (accountType.equals(serviceInfo.type.type)) {
5153 if (serviceInfo.uid == callingUid) {
5154 return SIGNATURE_CHECK_UID_MATCH;
5155 }
5156 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5157 if (sigChk == PackageManager.SIGNATURE_MATCH) {
5158 return SIGNATURE_CHECK_MATCH;
5159 }
5160 }
5161 }
5162 return SIGNATURE_CHECK_MISMATCH;
5163 }
5164
5165 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005166 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5167 if (accountType == null) {
5168 return false;
5169 } else {
5170 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5171 }
5172 }
5173
Svetoslavf3f02ac2015-09-08 14:36:35 -07005174 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5175 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005176 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005177 }
5178
5179 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005180 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005181 }
5182
5183 private List<String> getTypesForCaller(
5184 int callingUid, int userId, boolean isOtherwisePermitted) {
5185 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005186 long identityToken = Binder.clearCallingIdentity();
5187 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5188 try {
5189 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5190 } finally {
5191 Binder.restoreCallingIdentity(identityToken);
5192 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005193 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005194 serviceInfos) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005195 if (isOtherwisePermitted || (mPackageManager.checkSignatures(serviceInfo.uid,
5196 callingUid) == PackageManager.SIGNATURE_MATCH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005197 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005198 }
5199 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005200 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005201 }
5202
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005203 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5204 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5205 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5206 if (account.name.equals(accountName)) {
5207 return true;
5208 }
5209 }
5210 }
5211 return false;
5212 }
5213
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005214 private static void checkManageUsersPermission(String message) {
5215 if (ActivityManager.checkComponentPermission(
5216 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5217 != PackageManager.PERMISSION_GRANTED) {
5218 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5219 }
5220 }
5221
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005222 private static void checkManageOrCreateUsersPermission(String message) {
5223 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5224 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5225 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5226 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5227 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5228 + message);
5229 }
5230 }
5231
Amith Yamasani04e0d262012-02-14 11:50:53 -08005232 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5233 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005234 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005235 return true;
5236 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005237 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005238 synchronized (accounts.dbLock) {
5239 synchronized (accounts.cacheLock) {
5240 long grantsCount;
5241 if (authTokenType != null) {
5242 grantsCount = accounts.accountsDb
5243 .findMatchingGrantsCount(callerUid, authTokenType, account);
5244 } else {
5245 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5246 account);
5247 }
5248 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005249
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005250 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5251 // TODO: Skip this check when running automated tests. Replace this
5252 // with a more general solution.
5253 Log.d(TAG, "no credentials permission for usage of " + account + ", "
5254 + authTokenType + " by uid " + callerUid
5255 + " but ignoring since device is in test harness.");
5256 return true;
5257 }
5258 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005259 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005260 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005261 }
5262
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005263 private boolean isSystemUid(int callingUid) {
5264 String[] packages = null;
5265 long ident = Binder.clearCallingIdentity();
5266 try {
5267 packages = mPackageManager.getPackagesForUid(callingUid);
5268 } finally {
5269 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005270 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005271 if (packages != null) {
5272 for (String name : packages) {
5273 try {
5274 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5275 if (packageInfo != null
5276 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5277 != 0) {
5278 return true;
5279 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005280 } catch (NameNotFoundException e) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005281 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5282 }
5283 }
5284 } else {
5285 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005286 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005287 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005288 }
5289
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005290 /** Succeeds if any of the specified permissions are granted. */
5291 private void checkReadAccountsPermitted(
5292 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005293 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005294 int userId,
5295 String opPackageName) {
5296 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005297 String msg = String.format(
5298 "caller uid %s cannot access %s accounts",
5299 callingUid,
5300 accountType);
5301 Log.w(TAG, " " + msg);
5302 throw new SecurityException(msg);
5303 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005304 }
5305
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005306 private boolean canUserModifyAccounts(int userId, int callingUid) {
5307 // the managing app can always modify accounts
5308 if (isProfileOwner(callingUid)) {
5309 return true;
5310 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005311 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5312 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5313 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005314 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005315 return true;
5316 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005317
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005318 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5319 // the managing app can always modify accounts
5320 if (isProfileOwner(callingUid)) {
5321 return true;
5322 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005323 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5324 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005325 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005326 if (typesArray == null) {
5327 return true;
5328 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005329 for (String forbiddenType : typesArray) {
5330 if (forbiddenType.equals(accountType)) {
5331 return false;
5332 }
5333 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005334 return true;
5335 }
5336
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005337 private boolean isProfileOwner(int uid) {
5338 final DevicePolicyManagerInternal dpmi =
5339 LocalServices.getService(DevicePolicyManagerInternal.class);
5340 return (dpmi != null)
5341 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5342 }
5343
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005344 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005345 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5346 throws RemoteException {
5347 final int callingUid = getCallingUid();
5348
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005349 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005350 throw new SecurityException();
5351 }
5352
5353 if (value) {
5354 grantAppPermission(account, authTokenType, uid);
5355 } else {
5356 revokeAppPermission(account, authTokenType, uid);
5357 }
5358 }
5359
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005360 /**
5361 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5362 * <p>
5363 * Although this is public it can only be accessed via the AccountManagerService object
5364 * which is in the system. This means we don't need to protect it with permissions.
5365 * @hide
5366 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005367 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005368 if (account == null || authTokenType == null) {
5369 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005370 return;
5371 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005372 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005373 synchronized (accounts.dbLock) {
5374 synchronized (accounts.cacheLock) {
5375 long accountId = accounts.accountsDb.findDeAccountId(account);
5376 if (accountId >= 0) {
5377 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5378 }
5379 cancelNotification(
5380 getCredentialPermissionNotificationId(account, authTokenType, uid),
5381 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005382
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005383 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5384 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005385 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005386
5387 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5388 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5389 : mAppPermissionChangeListeners) {
5390 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5391 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005392 }
5393
5394 /**
5395 * Don't allow callers with the given uid permission to get credentials for
5396 * account/authTokenType.
5397 * <p>
5398 * Although this is public it can only be accessed via the AccountManagerService object
5399 * which is in the system. This means we don't need to protect it with permissions.
5400 * @hide
5401 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005402 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005403 if (account == null || authTokenType == null) {
5404 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005405 return;
5406 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005407 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005408 synchronized (accounts.dbLock) {
5409 synchronized (accounts.cacheLock) {
5410 accounts.accountsDb.beginTransaction();
5411 try {
5412 long accountId = accounts.accountsDb.findDeAccountId(account);
5413 if (accountId >= 0) {
5414 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5415 accountId, authTokenType, uid);
5416 accounts.accountsDb.setTransactionSuccessful();
5417 }
5418 } finally {
5419 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005420 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005421
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005422 cancelNotification(
5423 getCredentialPermissionNotificationId(account, authTokenType, uid),
5424 UserHandle.of(accounts.userId));
5425 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005426 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005427
5428 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5429 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5430 : mAppPermissionChangeListeners) {
5431 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5432 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005433 }
Fred Quintana56285a62010-12-02 14:20:51 -08005434
Amith Yamasani04e0d262012-02-14 11:50:53 -08005435 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5436 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005437 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005438 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005439 for (Account curAccount : oldAccountsForType) {
5440 if (!curAccount.equals(account)) {
5441 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005442 }
5443 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005444 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005445 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005446 } else {
5447 Account[] newAccountsForType = new Account[newAccountsList.size()];
5448 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005449 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005450 }
Fred Quintana56285a62010-12-02 14:20:51 -08005451 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005452 accounts.userDataCache.remove(account);
5453 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005454 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005455 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005456 }
5457
5458 /**
5459 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005460 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5461 * processes and if you will return this account to apps you should return the result.
5462 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005463 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005464 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005465 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005466 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5467 Account[] newAccountsForType = new Account[oldLength + 1];
5468 if (accountsForType != null) {
5469 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005470 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005471 String token = account.getAccessId() != null ? account.getAccessId()
5472 : UUID.randomUUID().toString();
5473 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005474 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005475 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005476 }
5477
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005478 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005479 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005480 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005481 String visibilityFilterPackage = callingPackage;
5482 if (visibilityFilterPackage == null) {
5483 visibilityFilterPackage = getPackageNameForUid(callingUid);
5484 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005485 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005486 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005487 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005488 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5489 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5490 || (includeManagedNotVisible
5491 && (visibility
5492 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5493 firstPass.put(account, visibility);
5494 }
5495 }
5496 Map<Account, Integer> secondPass =
5497 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5498
5499 Account[] filtered = new Account[secondPass.size()];
5500 filtered = secondPass.keySet().toArray(filtered);
5501 return filtered;
5502 }
5503
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005504 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005505 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005506 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005507 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005508 // first part is to filter shared accounts.
5509 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005510 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005511 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005512 return unfiltered;
5513 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005514 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005515 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005516 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005517 if (packages == null) {
5518 packages = new String[] {};
5519 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005520 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005521 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005522 // This might be a temporary way to specify a visible list
5523 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005524 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5525 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005526 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005527 return unfiltered;
5528 }
5529 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005530 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005531 if (ArrayUtils.isEmpty(sharedAccounts)) {
5532 return unfiltered;
5533 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005534 String requiredAccountType = "";
5535 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005536 // If there's an explicit callingPackage specified, check if that package
5537 // opted in to see restricted accounts.
5538 if (callingPackage != null) {
5539 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005540 if (pi != null && pi.restrictedAccountType != null) {
5541 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005542 }
5543 } else {
5544 // Otherwise check if the callingUid has a package that has opted in
5545 for (String packageName : packages) {
5546 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5547 if (pi != null && pi.restrictedAccountType != null) {
5548 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005549 break;
5550 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005551 }
5552 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005553 } catch (NameNotFoundException e) {
5554 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005555 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005556 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005557 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5558 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005559 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005560 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005561 } else {
5562 boolean found = false;
5563 for (Account shared : sharedAccounts) {
5564 if (shared.equals(account)) {
5565 found = true;
5566 break;
5567 }
5568 }
5569 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005570 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005571 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005572 }
5573 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005574 return filtered;
5575 } else {
5576 return unfiltered;
5577 }
5578 }
5579
Amith Yamasani27db4682013-03-30 17:07:47 -07005580 /*
5581 * packageName can be null. If not null, it should be used to filter out restricted accounts
5582 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005583 *
5584 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5585 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005586 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005587 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005588 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005589 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005590 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5591 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005592 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005593 Account[] accounts;
5594 synchronized (userAccounts.cacheLock) {
5595 accounts = userAccounts.accountCache.get(accountType);
5596 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005597 if (accounts == null) {
5598 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005599 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005600 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5601 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005602 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005603 } else {
5604 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005605 Account[] accountsArray;
5606 synchronized (userAccounts.cacheLock) {
5607 for (Account[] accounts : userAccounts.accountCache.values()) {
5608 totalLength += accounts.length;
5609 }
5610 if (totalLength == 0) {
5611 return EMPTY_ACCOUNT_ARRAY;
5612 }
5613 accountsArray = new Account[totalLength];
5614 totalLength = 0;
5615 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5616 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5617 accountsOfType.length);
5618 totalLength += accountsOfType.length;
5619 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005620 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005621 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005622 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005623 }
5624 }
5625
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005626 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005627 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005628 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005629 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005630 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005631 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005632 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005633 }
5634 if (value == null) {
5635 userDataForAccount.remove(key);
5636 } else {
5637 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005638 }
5639 }
5640
Carlos Valdivia91979be2015-05-22 14:11:35 -07005641 protected String readCachedTokenInternal(
5642 UserAccounts accounts,
5643 Account account,
5644 String tokenType,
5645 String callingPackage,
5646 byte[] pkgSigDigest) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005647 synchronized (accounts.dbLock) {
5648 synchronized (accounts.cacheLock) {
5649 return accounts.accountTokenCaches.get(
5650 account, tokenType, callingPackage, pkgSigDigest);
5651 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07005652 }
5653 }
5654
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005655 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005656 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005657 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005658 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005659 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005660 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005661 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005662 }
5663 if (value == null) {
5664 authTokensForAccount.remove(key);
5665 } else {
5666 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005667 }
5668 }
5669
Amith Yamasani04e0d262012-02-14 11:50:53 -08005670 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5671 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005672 // Fast path - check if account is already cached
5673 synchronized (accounts.cacheLock) {
5674 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5675 if (authTokensForAccount != null) {
5676 return authTokensForAccount.get(authTokenType);
5677 }
5678 }
5679 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005680 synchronized (accounts.dbLock) {
5681 synchronized (accounts.cacheLock) {
5682 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5683 if (authTokensForAccount == null) {
5684 // need to populate the cache for this account
5685 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
5686 accounts.authTokenCache.put(account, authTokensForAccount);
5687 }
5688 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08005689 }
Fred Quintana56285a62010-12-02 14:20:51 -08005690 }
5691 }
5692
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005693 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
5694 Map<String, String> userDataForAccount;
5695 // Fast path - check if data is already cached
5696 synchronized (accounts.cacheLock) {
5697 userDataForAccount = accounts.userDataCache.get(account);
5698 }
5699 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00005700 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005701 synchronized (accounts.dbLock) {
5702 synchronized (accounts.cacheLock) {
5703 userDataForAccount = accounts.userDataCache.get(account);
5704 if (userDataForAccount == null) {
5705 // need to populate the cache for this account
5706 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
5707 accounts.userDataCache.put(account, userDataForAccount);
5708 }
5709 }
5710 }
Fred Quintana56285a62010-12-02 14:20:51 -08005711 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005712 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005713 }
5714
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005715 private Context getContextForUser(UserHandle user) {
5716 try {
5717 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5718 } catch (NameNotFoundException e) {
5719 // Default to mContext, not finding the package system is running as is unlikely.
5720 return mContext;
5721 }
5722 }
Sandra Kwan78812282015-11-04 11:19:47 -08005723
5724 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5725 try {
5726 response.onResult(result);
5727 } catch (RemoteException e) {
5728 // if the caller is dead then there is no one to care about remote
5729 // exceptions
5730 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5731 Log.v(TAG, "failure while notifying response", e);
5732 }
5733 }
5734 }
5735
5736 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5737 String errorMessage) {
5738 try {
5739 response.onError(errorCode, errorMessage);
5740 } catch (RemoteException e) {
5741 // if the caller is dead then there is no one to care about remote
5742 // exceptions
5743 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5744 Log.v(TAG, "failure while notifying response", e);
5745 }
5746 }
5747 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005748
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005749 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07005750 private final Object mLock = new Object();
5751
5752 @GuardedBy("mLock")
5753 private AccountManagerBackupHelper mBackupHelper;
5754
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005755 @Override
5756 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
5757 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
5758 if (account == null) {
5759 Slog.w(TAG, "account cannot be null");
5760 return;
5761 }
5762 if (packageName == null) {
5763 Slog.w(TAG, "packageName cannot be null");
5764 return;
5765 }
5766 if (userId < UserHandle.USER_SYSTEM) {
5767 Slog.w(TAG, "user id must be concrete");
5768 return;
5769 }
5770 if (callback == null) {
5771 Slog.w(TAG, "callback cannot be null");
5772 return;
5773 }
5774
Svet Ganovf6d424f12016-09-20 20:18:53 -07005775 if (AccountManagerService.this.hasAccountAccess(account, packageName,
5776 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005777 Bundle result = new Bundle();
5778 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
5779 callback.sendResult(result);
5780 return;
5781 }
5782
5783 final int uid;
5784 try {
5785 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
5786 } catch (NameNotFoundException e) {
5787 Slog.e(TAG, "Unknown package " + packageName);
5788 return;
5789 }
5790
5791 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07005792 final UserAccounts userAccounts;
5793 synchronized (mUsers) {
5794 userAccounts = mUsers.get(userId);
5795 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04005796 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07005797 doNotification(userAccounts, account, null, intent, packageName, userId);
5798 }
5799
5800 @Override
5801 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
5802 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5803 mAppPermissionChangeListeners.add(listener);
5804 }
5805
5806 @Override
5807 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
5808 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005809 }
Svet Ganov5d09c992016-09-07 09:57:41 -07005810
5811 @Override
5812 public byte[] backupAccountAccessPermissions(int userId) {
5813 synchronized (mLock) {
5814 if (mBackupHelper == null) {
5815 mBackupHelper = new AccountManagerBackupHelper(
5816 AccountManagerService.this, this);
5817 }
5818 return mBackupHelper.backupAccountAccessPermissions(userId);
5819 }
5820 }
5821
5822 @Override
5823 public void restoreAccountAccessPermissions(byte[] data, int userId) {
5824 synchronized (mLock) {
5825 if (mBackupHelper == null) {
5826 mBackupHelper = new AccountManagerBackupHelper(
5827 AccountManagerService.this, this);
5828 }
5829 mBackupHelper.restoreAccountAccessPermissions(data, userId);
5830 }
5831 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005832 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07005833
5834 @VisibleForTesting
5835 static class Injector {
5836 private final Context mContext;
5837
5838 public Injector(Context context) {
5839 mContext = context;
5840 }
5841
5842 Looper getMessageHandlerLooper() {
5843 ServiceThread serviceThread = new ServiceThread(TAG,
5844 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
5845 serviceThread.start();
5846 return serviceThread.getLooper();
5847 }
5848
5849 Context getContext() {
5850 return mContext;
5851 }
5852
5853 void addLocalService(AccountManagerInternal service) {
5854 LocalServices.addService(AccountManagerInternal.class, service);
5855 }
5856
5857 String getDeDatabaseName(int userId) {
5858 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
5859 AccountsDb.DE_DATABASE_NAME);
5860 return databaseFile.getPath();
5861 }
5862
5863 String getCeDatabaseName(int userId) {
5864 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
5865 AccountsDb.CE_DATABASE_NAME);
5866 return databaseFile.getPath();
5867 }
5868
5869 String getPreNDatabaseName(int userId) {
5870 File systemDir = Environment.getDataSystemDirectory();
5871 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
5872 PRE_N_DATABASE_NAME);
5873 if (userId == 0) {
5874 // Migrate old file, if it exists, to the new location.
5875 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005876 // accidentally created in the old location,
5877 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07005878 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
5879 if (oldFile.exists() && !databaseFile.exists()) {
5880 // Check for use directory; create if it doesn't exist, else renameTo will fail
5881 File userDir = Environment.getUserSystemDirectory(userId);
5882 if (!userDir.exists()) {
5883 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005884 throw new IllegalStateException(
5885 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07005886 }
5887 }
5888 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005889 throw new IllegalStateException(
5890 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07005891 }
5892 }
5893 }
5894 return databaseFile.getPath();
5895 }
5896
5897 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
5898 return new AccountAuthenticatorCache(mContext);
5899 }
5900
5901 INotificationManager getNotificationManager() {
5902 return NotificationManager.getService();
5903 }
5904 }
Fred Quintana60307342009-03-24 22:48:12 -07005905}