blob: 426a0c157aec50b3bf9c28e13c8831f27fc261a3 [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070025import android.accounts.AccountManagerInternal;
sunjianf29d5492017-05-11 15:42:31 -070026import android.accounts.AccountManagerResponse;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070028import android.accounts.CantAddAccountActivity;
sunjianf29d5492017-05-11 15:42:31 -070029import android.accounts.ChooseAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080030import android.accounts.GrantCredentialsPermissionActivity;
31import android.accounts.IAccountAuthenticator;
32import android.accounts.IAccountAuthenticatorResponse;
33import android.accounts.IAccountManager;
34import android.accounts.IAccountManagerResponse;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070035import android.annotation.IntRange;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070036import android.annotation.NonNull;
Svet Ganovf6d424f12016-09-20 20:18:53 -070037import android.annotation.Nullable;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080038import android.app.ActivityManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070039import android.app.ActivityThread;
Svetoslavf3f02ac2015-09-08 14:36:35 -070040import android.app.AppOpsManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070041import android.app.INotificationManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.app.Notification;
43import android.app.NotificationManager;
44import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000045import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010046import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000047import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070049import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070050import android.content.Context;
51import android.content.Intent;
52import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070053import android.content.IntentSender;
Fred Quintanab839afc2009-10-14 15:57:28 -070054import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080055import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.content.pm.ApplicationInfo;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070057import android.content.pm.IPackageManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070058import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070060import android.content.pm.PackageManager.NameNotFoundException;
Dan Cashman303c4bb2018-04-10 07:41:16 -070061import android.content.pm.PackageManagerInternal;
62import android.content.pm.PackageParser;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070063import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070064import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070065import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070066import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070067import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070068import android.database.Cursor;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070069import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070070import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080072import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070073import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070074import android.os.IBinder;
75import android.os.Looper;
76import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070077import android.os.Parcel;
sunjianf29d5492017-05-11 15:42:31 -070078import android.os.Parcelable;
Amith Yamasani27db4682013-03-30 17:07:47 -070079import android.os.Process;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070080import android.os.RemoteCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import android.os.RemoteException;
Hongming Jin8e2bfc12018-05-30 11:01:06 -070082import android.os.ResultReceiver;
83import android.os.ShellCallback;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080084import android.os.StrictMode;
Fred Quintanaa698f422009-04-08 19:14:54 -070085import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070086import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070087import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070088import android.text.TextUtils;
89import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070090import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070091import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080092import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070093import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070094
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070095import com.android.internal.R;
Svet Ganov5d09c992016-09-07 09:57:41 -070096import com.android.internal.annotations.GuardedBy;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070097import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070098import com.android.internal.content.PackageMonitor;
Chris Wren282cfef2017-03-27 15:01:44 -040099import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500100import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800101import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600102import com.android.internal.util.DumpUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800103import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700104import com.android.internal.util.Preconditions;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000105import com.android.server.LocalServices;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700106import com.android.server.ServiceThread;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600107import com.android.server.SystemService;
108
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700109import com.google.android.collect.Lists;
110import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700111
Oscar Montemayora8529f62009-11-18 10:14:20 -0800112import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700113import java.io.FileDescriptor;
114import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800115import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700116import java.security.MessageDigest;
117import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700118import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700119import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800120import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700121import java.util.Collection;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700122import java.util.Collections;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700123import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700124import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700125import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800126import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700127import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800128import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800129import java.util.Map.Entry;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700130import java.util.Objects;
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700131import java.util.Set;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700132import java.util.UUID;
Svet Ganovf6d424f12016-09-20 20:18:53 -0700133import java.util.concurrent.CopyOnWriteArrayList;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700134import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700135
Fred Quintana60307342009-03-24 22:48:12 -0700136/**
137 * A system service that provides account, password, and authtoken management for all
138 * accounts on the device. Some of these calls are implemented with the help of the corresponding
139 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
140 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700141 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700142 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700143 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700144public class AccountManagerService
145 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800146 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700147 private static final String TAG = "AccountManagerService";
148
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600149 public static class Lifecycle extends SystemService {
150 private AccountManagerService mService;
151
152 public Lifecycle(Context context) {
153 super(context);
154 }
155
156 @Override
157 public void onStart() {
Fyodor Kupolovda993802016-09-21 14:47:10 -0700158 mService = new AccountManagerService(new Injector(getContext()));
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600159 publishBinderService(Context.ACCOUNT_SERVICE, mService);
160 }
161
162 @Override
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600163 public void onUnlockUser(int userHandle) {
164 mService.onUnlockUser(userHandle);
165 }
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700166
167 @Override
Fyodor Kupolovce25ed22017-05-04 11:44:31 -0700168 public void onStopUser(int userHandle) {
Fyodor Kupolov945c97e2017-06-21 17:45:19 -0700169 Slog.i(TAG, "onStopUser " + userHandle);
170 mService.purgeUserData(userHandle);
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700171 }
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600172 }
173
Svet Ganov5d09c992016-09-07 09:57:41 -0700174 final Context mContext;
Fred Quintana60307342009-03-24 22:48:12 -0700175
Fred Quintana56285a62010-12-02 14:20:51 -0800176 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700177 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700178 private UserManager mUserManager;
Fyodor Kupolovda993802016-09-21 14:47:10 -0700179 private final Injector mInjector;
Fred Quintana56285a62010-12-02 14:20:51 -0800180
Svet Ganov5d09c992016-09-07 09:57:41 -0700181 final MessageHandler mHandler;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700182
Fred Quintana60307342009-03-24 22:48:12 -0700183 // Messages that can be sent on mHandler
184 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700185 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700186
Fred Quintana56285a62010-12-02 14:20:51 -0800187 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700188 private static final String PRE_N_DATABASE_NAME = "accounts.db";
Fred Quintana7be59642009-08-24 18:29:25 -0700189 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800190
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800191 private static final int SIGNATURE_CHECK_MISMATCH = 0;
192 private static final int SIGNATURE_CHECK_MATCH = 1;
193 private static final int SIGNATURE_CHECK_UID_MATCH = 2;
194
Carlos Valdivia91979be2015-05-22 14:11:35 -0700195 static {
196 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Christopher Tatebded68f2017-02-21 11:41:55 -0800197 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
198 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700199 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700200
201 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700202
Amith Yamasani04e0d262012-02-14 11:50:53 -0800203 static class UserAccounts {
204 private final int userId;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700205 final AccountsDb accountsDb;
Chris Wren717a8812017-03-31 15:34:39 -0400206 private final HashMap<Pair<Pair<Account, String>, Integer>, NotificationId>
207 credentialsPermissionNotificationIds = new HashMap<>();
208 private final HashMap<Account, NotificationId> signinRequiredNotificationIds
209 = new HashMap<>();
Svet Ganov5d09c992016-09-07 09:57:41 -0700210 final Object cacheLock = new Object();
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700211 final Object dbLock = new Object(); // if needed, dbLock must be obtained before cacheLock
Amith Yamasani04e0d262012-02-14 11:50:53 -0800212 /** protected by the {@link #cacheLock} */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700213 final HashMap<String, Account[]> accountCache = new LinkedHashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800214 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700215 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700217 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700218 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700219 private final TokenCache accountTokenCaches = new TokenCache();
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700220 /** protected by the {@link #cacheLock} */
221 private final Map<Account, Map<String, Integer>> visibilityCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700222
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700223 /** protected by the {@link #mReceiversForType},
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700224 * type -> (packageName -> number of active receivers)
225 * type == null is used to get notifications about all account types
226 */
227 private final Map<String, Map<String, Integer>> mReceiversForType = new HashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800228
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700229 /**
230 * protected by the {@link #cacheLock}
231 *
232 * Caches the previous names associated with an account. Previous names
233 * should be cached because we expect that when an Account is renamed,
234 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
235 * want to know if the accounts they care about have been renamed.
236 *
237 * The previous names are wrapped in an {@link AtomicReference} so that
238 * we can distinguish between those accounts with no previous names and
239 * those whose previous names haven't been cached (yet).
240 */
241 private final HashMap<Account, AtomicReference<String>> previousNameCache =
242 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800243
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700244 private int debugDbInsertionPoint = -1;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700245 private SQLiteStatement statementForLogging; // TODO Move to AccountsDb
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700246
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700247 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800248 this.userId = userId;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700249 synchronized (dbLock) {
250 synchronized (cacheLock) {
251 accountsDb = AccountsDb.create(context, userId, preNDbFile, deDbFile);
252 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800253 }
254 }
255 }
256
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700257 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600258 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -0700259 // Not thread-safe. Only use in synchronized context
260 private final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Svet Ganovf6d424f12016-09-20 20:18:53 -0700261 private CopyOnWriteArrayList<AccountManagerInternal.OnAppPermissionChangeListener>
262 mAppPermissionChangeListeners = new CopyOnWriteArrayList<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800263
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700264 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700265 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700266
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700267 /**
268 * This should only be called by system code. One should only call this after the service
269 * has started.
270 * @return a reference to the AccountManagerService instance
271 * @hide
272 */
273 public static AccountManagerService getSingleton() {
274 return sThis.get();
275 }
Fred Quintana60307342009-03-24 22:48:12 -0700276
Fyodor Kupolovda993802016-09-21 14:47:10 -0700277 public AccountManagerService(Injector injector) {
278 mInjector = injector;
279 mContext = injector.getContext();
280 mPackageManager = mContext.getPackageManager();
Svetoslavf3f02ac2015-09-08 14:36:35 -0700281 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fyodor Kupolovda993802016-09-21 14:47:10 -0700282 mHandler = new MessageHandler(injector.getMessageHandlerLooper());
283 mAuthenticatorCache = mInjector.getAccountAuthenticatorCache();
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800284 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700285
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700286 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800287
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800288 IntentFilter intentFilter = new IntentFilter();
289 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
290 intentFilter.addDataScheme("package");
291 mContext.registerReceiver(new BroadcastReceiver() {
292 @Override
293 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700294 // Don't delete accounts when updating a authenticator's
295 // package.
296 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700297 /* Purging data requires file io, don't block the main thread. This is probably
298 * less than ideal because we are introducing a race condition where old grants
299 * could be exercised until they are purged. But that race condition existed
300 * anyway with the broadcast receiver.
301 *
302 * Ideally, we would completely clear the cache, purge data from the database,
303 * and then rebuild the cache. All under the cache lock. But that change is too
304 * large at this point.
305 */
Dmitry Dementyev0b676422017-03-09 11:51:26 -0800306 final String removedPackageName = intent.getData().getSchemeSpecificPart();
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700307 Runnable purgingRunnable = new Runnable() {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700308 @Override
309 public void run() {
310 purgeOldGrantsAll();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800311 // Notify authenticator about removed app?
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800312 removeVisibilityValuesForPackage(removedPackageName);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700313 }
314 };
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700315 mHandler.post(purgingRunnable);
Carlos Valdivia23f58262014-09-05 10:52:41 -0700316 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800317 }
318 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800319
Fyodor Kupolovda993802016-09-21 14:47:10 -0700320 injector.addLocalService(new AccountManagerInternalImpl());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700321
Fyodor Kupolov945c97e2017-06-21 17:45:19 -0700322 IntentFilter userFilter = new IntentFilter();
323 userFilter.addAction(Intent.ACTION_USER_REMOVED);
324 mContext.registerReceiverAsUser(new BroadcastReceiver() {
325 @Override
326 public void onReceive(Context context, Intent intent) {
327 String action = intent.getAction();
328 if (Intent.ACTION_USER_REMOVED.equals(action)) {
329 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
330 if (userId < 1) return;
331 Slog.i(TAG, "User " + userId + " removed");
332 purgeUserData(userId);
333 }
334 }
335 }, UserHandle.ALL, userFilter, null, null);
336
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700337 // Need to cancel account request notifications if the update/install can access the account
338 new PackageMonitor() {
339 @Override
340 public void onPackageAdded(String packageName, int uid) {
341 // Called on a handler, and running as the system
342 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
343 }
344
345 @Override
346 public void onPackageUpdateFinished(String packageName, int uid) {
347 // Called on a handler, and running as the system
348 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
349 }
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700350 }.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700351
352 // Cancel account request notification if an app op was preventing the account access
353 mAppOpsManager.startWatchingMode(AppOpsManager.OP_GET_ACCOUNTS, null,
354 new AppOpsManager.OnOpChangedInternalListener() {
355 @Override
356 public void onOpChanged(int op, String packageName) {
357 try {
358 final int userId = ActivityManager.getCurrentUser();
359 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
360 final int mode = mAppOpsManager.checkOpNoThrow(
361 AppOpsManager.OP_GET_ACCOUNTS, uid, packageName);
362 if (mode == AppOpsManager.MODE_ALLOWED) {
363 final long identity = Binder.clearCallingIdentity();
364 try {
365 cancelAccountAccessRequestNotificationIfNeeded(packageName, uid, true);
366 } finally {
367 Binder.restoreCallingIdentity(identity);
368 }
369 }
370 } catch (NameNotFoundException e) {
371 /* ignore */
372 }
373 }
374 });
375
376 // Cancel account request notification if a permission was preventing the account access
377 mPackageManager.addOnPermissionsChangeListener(
378 (int uid) -> {
379 Account[] accounts = null;
380 String[] packageNames = mPackageManager.getPackagesForUid(uid);
381 if (packageNames != null) {
382 final int userId = UserHandle.getUserId(uid);
383 final long identity = Binder.clearCallingIdentity();
384 try {
385 for (String packageName : packageNames) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800386 // if app asked for permission we need to cancel notification even
387 // for O+ applications.
388 if (mPackageManager.checkPermission(
389 Manifest.permission.GET_ACCOUNTS,
390 packageName) != PackageManager.PERMISSION_GRANTED) {
391 continue;
392 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700393
394 if (accounts == null) {
395 accounts = getAccountsAsUser(null, userId, "android");
396 if (ArrayUtils.isEmpty(accounts)) {
397 return;
398 }
399 }
400
401 for (Account account : accounts) {
402 cancelAccountAccessRequestNotificationIfNeeded(
403 account, uid, packageName, true);
404 }
405 }
406 } finally {
407 Binder.restoreCallingIdentity(identity);
408 }
409 }
410 });
411 }
412
Hongming Jin8e2bfc12018-05-30 11:01:06 -0700413
414 boolean getBindInstantServiceAllowed(int userId) {
415 return mAuthenticatorCache.getBindInstantServiceAllowed(userId);
416 }
417
418 void setBindInstantServiceAllowed(int userId, boolean allowed) {
419 mAuthenticatorCache.setBindInstantServiceAllowed(userId, allowed);
420 }
421
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700422 private void cancelAccountAccessRequestNotificationIfNeeded(int uid,
423 boolean checkAccess) {
424 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
425 for (Account account : accounts) {
426 cancelAccountAccessRequestNotificationIfNeeded(account, uid, checkAccess);
427 }
428 }
429
430 private void cancelAccountAccessRequestNotificationIfNeeded(String packageName, int uid,
431 boolean checkAccess) {
432 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
433 for (Account account : accounts) {
434 cancelAccountAccessRequestNotificationIfNeeded(account, uid, packageName, checkAccess);
435 }
436 }
437
438 private void cancelAccountAccessRequestNotificationIfNeeded(Account account, int uid,
439 boolean checkAccess) {
440 String[] packageNames = mPackageManager.getPackagesForUid(uid);
441 if (packageNames != null) {
442 for (String packageName : packageNames) {
443 cancelAccountAccessRequestNotificationIfNeeded(account, uid,
444 packageName, checkAccess);
445 }
446 }
447 }
448
449 private void cancelAccountAccessRequestNotificationIfNeeded(Account account,
450 int uid, String packageName, boolean checkAccess) {
451 if (!checkAccess || hasAccountAccess(account, packageName,
452 UserHandle.getUserHandleForUid(uid))) {
453 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -0700454 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700455 UserHandle.getUserHandleForUid(uid));
456 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800457 }
458
Dianne Hackborn164371f2013-10-01 19:10:13 -0700459 @Override
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800460 public boolean addAccountExplicitlyWithVisibility(Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800461 Bundle extras, Map packageToVisibility) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800462 Bundle.setDefusable(extras, true);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700463 int callingUid = Binder.getCallingUid();
464 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800465 if (Log.isLoggable(TAG, Log.VERBOSE)) {
466 Log.v(TAG, "addAccountExplicitly: " + account + ", caller's uid " + callingUid
467 + ", pid " + Binder.getCallingPid());
468 }
469 Preconditions.checkNotNull(account, "account cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800470 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
471 String msg = String.format("uid %s cannot explicitly add accounts of type: %s",
472 callingUid, account.type);
473 throw new SecurityException(msg);
474 }
475 /*
476 * Child users are not allowed to add accounts. Only the accounts that are shared by the
477 * parent profile can be added to child profile.
478 *
479 * TODO: Only allow accounts that were shared to be added by a limited user.
480 */
481 // fails if the account already exists
482 long identityToken = clearCallingIdentity();
483 try {
484 UserAccounts accounts = getUserAccounts(userId);
485 return addAccountInternal(accounts, account, password, extras, callingUid,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800486 (Map<String, Integer>) packageToVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800487 } finally {
488 restoreCallingIdentity(identityToken);
489 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700490 }
491
492 @Override
Dmitry Dementyev52745472016-12-02 10:27:45 -0800493 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
494 String accountType) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800495 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700496 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800497 boolean isSystemUid = UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700498 List<String> managedTypes = getTypesForCaller(callingUid, userId, isSystemUid);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800499
500 if ((accountType != null && !managedTypes.contains(accountType))
501 || (accountType == null && !isSystemUid)) {
502 throw new SecurityException(
503 "getAccountsAndVisibilityForPackage() called from unauthorized uid "
504 + callingUid + " with packageName=" + packageName);
505 }
506 if (accountType != null) {
507 managedTypes = new ArrayList<String>();
508 managedTypes.add(accountType);
509 }
510
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800511 long identityToken = clearCallingIdentity();
512 try {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700513 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800514 return getAccountsAndVisibilityForPackage(packageName, managedTypes, callingUid,
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700515 accounts);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800516 } finally {
517 restoreCallingIdentity(identityToken);
518 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800519 }
520
521 /*
522 * accountTypes may not be null
523 */
524 private Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
525 List<String> accountTypes, Integer callingUid, UserAccounts accounts) {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700526 if (!packageExistsForUser(packageName, accounts.userId)) {
527 Log.d(TAG, "Package not found " + packageName);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800528 return new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800529 }
530
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800531 Map<Account, Integer> result = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800532 for (String accountType : accountTypes) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700533 synchronized (accounts.dbLock) {
534 synchronized (accounts.cacheLock) {
535 final Account[] accountsOfType = accounts.accountCache.get(accountType);
536 if (accountsOfType != null) {
537 for (Account account : accountsOfType) {
538 result.put(account,
539 resolveAccountVisibility(account, packageName, accounts));
540 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800541 }
542 }
543 }
544 }
545 return filterSharedAccounts(accounts, result, callingUid, packageName);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800546 }
547
548 @Override
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800549 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700550 Preconditions.checkNotNull(account, "account cannot be null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700551 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700552 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800553 if (!isAccountManagedByCaller(account.type, callingUid, userId)
554 && !isSystemUid(callingUid)) {
555 String msg =
556 String.format("uid %s cannot get secrets for account %s", callingUid, account);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700557 throw new SecurityException(msg);
558 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700559
560 long identityToken = clearCallingIdentity();
561 try {
562 UserAccounts accounts = getUserAccounts(userId);
563 synchronized (accounts.dbLock) {
564 synchronized (accounts.cacheLock) {
565 return getPackagesAndVisibilityForAccountLocked(account, accounts);
566 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700567 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700568 } finally {
569 restoreCallingIdentity(identityToken);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700570 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700571
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800572 }
573
574 /**
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700575 * Returns Map with all package names and visibility values for given account.
576 * The method and returned map must be guarded by accounts.cacheLock
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800577 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800578 * @param account Account to get visibility values.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800579 * @param accounts UserAccount that currently hosts the account and application
580 *
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700581 * @return Map with cache for package names to visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800582 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700583 private @NonNull Map<String, Integer> getPackagesAndVisibilityForAccountLocked(Account account,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800584 UserAccounts accounts) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700585 Map<String, Integer> accountVisibility = accounts.visibilityCache.get(account);
586 if (accountVisibility == null) {
587 Log.d(TAG, "Visibility was not initialized");
588 accountVisibility = new HashMap<>();
589 accounts.visibilityCache.put(account, accountVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800590 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700591 return accountVisibility;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700592 }
593
594 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700595 public int getAccountVisibility(Account account, String packageName) {
596 Preconditions.checkNotNull(account, "account cannot be null");
597 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800598 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700599 int userId = UserHandle.getCallingUserId();
600 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800601 && !isSystemUid(callingUid)) {
602 String msg = String.format(
603 "uid %s cannot get secrets for accounts of type: %s",
604 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700605 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800606 throw new SecurityException(msg);
607 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700608 long identityToken = clearCallingIdentity();
609 try {
610 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyevcbe1bd12017-04-25 17:02:47 -0700611 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)) {
612 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
613 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
614 return visibility;
615 } else {
616 return AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
617 }
618 }
619 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName)) {
620 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
621 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
622 return visibility;
623 } else {
624 return AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
625 }
626 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700627 return resolveAccountVisibility(account, packageName, accounts);
628 } finally {
629 restoreCallingIdentity(identityToken);
630 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800631 }
632
633 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800634 * Method returns visibility for given account and package name.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800635 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800636 * @param account The account to check visibility.
637 * @param packageName Package name to check visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800638 * @param accounts UserAccount that currently hosts the account and application
639 *
640 * @return Visibility value, AccountManager.VISIBILITY_UNDEFINED if no value was stored.
641 *
642 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700643 private int getAccountVisibilityFromCache(Account account, String packageName,
644 UserAccounts accounts) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700645 synchronized (accounts.cacheLock) {
646 Map<String, Integer> accountVisibility =
647 getPackagesAndVisibilityForAccountLocked(account, accounts);
648 Integer visibility = accountVisibility.get(packageName);
649 return visibility != null ? visibility : AccountManager.VISIBILITY_UNDEFINED;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800650 }
651 }
652
653 /**
654 * Method which handles default values for Account visibility.
655 *
656 * @param account The account to check visibility.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800657 * @param packageName Package name to check visibility
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800658 * @param accounts UserAccount that currently hosts the account and application
659 *
660 * @return Visibility value, the method never returns AccountManager.VISIBILITY_UNDEFINED
661 *
662 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800663 private Integer resolveAccountVisibility(Account account, @NonNull String packageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800664 UserAccounts accounts) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800665 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800666 int uid = -1;
667 try {
668 long identityToken = clearCallingIdentity();
669 try {
670 uid = mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
671 } finally {
672 restoreCallingIdentity(identityToken);
673 }
674 } catch (NameNotFoundException e) {
675 Log.d(TAG, "Package not found " + e.getMessage());
676 return AccountManager.VISIBILITY_NOT_VISIBLE;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800677 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800678
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800679 // System visibility can not be restricted.
680 if (UserHandle.isSameApp(uid, Process.SYSTEM_UID)) {
681 return AccountManager.VISIBILITY_VISIBLE;
682 }
683
684 int signatureCheckResult =
685 checkPackageSignature(account.type, uid, accounts.userId);
686
687 // Authenticator can not restrict visibility to itself.
688 if (signatureCheckResult == SIGNATURE_CHECK_UID_MATCH) {
689 return AccountManager.VISIBILITY_VISIBLE; // Authenticator can always see the account
690 }
691
692 // Return stored value if it was set.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700693 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800694
695 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
696 return visibility;
697 }
698
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700699 boolean isPrivileged = isPermittedForPackage(packageName, uid, accounts.userId,
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800700 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
701
702 // Device/Profile owner gets visibility by default.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800703 if (isProfileOwner(uid)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800704 return AccountManager.VISIBILITY_VISIBLE;
705 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800706
707 boolean preO = isPreOApplication(packageName);
708 if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700709 || (preO && checkGetAccountsPermission(packageName, uid, accounts.userId))
710 || (checkReadContactsPermission(packageName, uid, accounts.userId)
711 && accountTypeManagesContacts(account.type, accounts.userId))
712 || isPrivileged) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800713 // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
714 // match.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700715 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800716 AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800717 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
718 visibility = AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
719 }
720 } else {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700721 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800722 AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800723 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
724 visibility = AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
725 }
726 }
727 return visibility;
728 }
729
730 /**
731 * Checks targetSdk for a package;
732 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800733 * @param packageName Package name
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800734 *
735 * @return True if package's target SDK is below {@link android.os.Build.VERSION_CODES#O}, or
736 * undefined
737 */
738 private boolean isPreOApplication(String packageName) {
739 try {
740 long identityToken = clearCallingIdentity();
741 ApplicationInfo applicationInfo;
742 try {
743 applicationInfo = mPackageManager.getApplicationInfo(packageName, 0);
744 } finally {
745 restoreCallingIdentity(identityToken);
746 }
747
748 if (applicationInfo != null) {
749 int version = applicationInfo.targetSdkVersion;
750 return version < android.os.Build.VERSION_CODES.O;
751 }
752 return true;
753 } catch (NameNotFoundException e) {
754 Log.d(TAG, "Package not found " + e.getMessage());
755 return true;
756 }
Dmitry Dementyev58fa83622016-12-20 18:08:51 -0800757 }
758
759 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700760 public boolean setAccountVisibility(Account account, String packageName, int newVisibility) {
761 Preconditions.checkNotNull(account, "account cannot be null");
762 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800763 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700764 int userId = UserHandle.getCallingUserId();
765 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800766 && !isSystemUid(callingUid)) {
767 String msg = String.format(
768 "uid %s cannot get secrets for accounts of type: %s",
769 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700770 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800771 throw new SecurityException(msg);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700772 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700773 long identityToken = clearCallingIdentity();
774 try {
775 UserAccounts accounts = getUserAccounts(userId);
776 return setAccountVisibility(account, packageName, newVisibility, true /* notify */,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700777 accounts);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700778 } finally {
779 restoreCallingIdentity(identityToken);
780 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700781 }
782
sunjian066aa5e2017-06-05 12:16:59 -0700783 private boolean isVisible(int visibility) {
784 return visibility == AccountManager.VISIBILITY_VISIBLE ||
785 visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
786 }
787
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700788 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800789 * Updates visibility for given account name and package.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700790 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800791 * @param account Account to update visibility.
792 * @param packageName Package name for which visibility is updated.
793 * @param newVisibility New visibility calue
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800794 * @param notify if the flag is set applications will get notification about visibility change
795 * @param accounts UserAccount that currently hosts the account and application
796 *
797 * @return True if account visibility was changed.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700798 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800799 private boolean setAccountVisibility(Account account, String packageName, int newVisibility,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800800 boolean notify, UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700801 synchronized (accounts.dbLock) {
802 synchronized (accounts.cacheLock) {
803 Map<String, Integer> packagesToVisibility;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700804 List<String> accountRemovedReceivers;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700805 if (notify) {
806 if (isSpecialPackageKey(packageName)) {
807 packagesToVisibility =
808 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700809 accountRemovedReceivers = getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700810 } else {
811 if (!packageExistsForUser(packageName, accounts.userId)) {
812 return false; // package is not installed.
813 }
814 packagesToVisibility = new HashMap<>();
815 packagesToVisibility.put(packageName,
816 resolveAccountVisibility(account, packageName, accounts));
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700817 accountRemovedReceivers = new ArrayList<>();
818 if (shouldNotifyPackageOnAccountRemoval(account, packageName, accounts)) {
819 accountRemovedReceivers.add(packageName);
820 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700821 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800822 } else {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700823 // Notifications will not be send - only used during add account.
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700824 if (!isSpecialPackageKey(packageName) &&
825 !packageExistsForUser(packageName, accounts.userId)) {
826 // package is not installed and not meta value.
827 return false;
Nicolas Prevotf7d8df12016-09-16 17:45:34 +0100828 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700829 packagesToVisibility = Collections.emptyMap();
830 accountRemovedReceivers = Collections.emptyList();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800831 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700832
833 if (!updateAccountVisibilityLocked(account, packageName, newVisibility, accounts)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800834 return false;
835 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800836
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700837 if (notify) {
838 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
839 .entrySet()) {
sunjian066aa5e2017-06-05 12:16:59 -0700840 int oldVisibility = packageToVisibility.getValue();
841 int currentVisibility =
842 resolveAccountVisibility(account, packageName, accounts);
843 if (isVisible(oldVisibility) != isVisible(currentVisibility)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700844 notifyPackage(packageToVisibility.getKey(), accounts);
845 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700846 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700847 for (String packageNameToNotify : accountRemovedReceivers) {
848 sendAccountRemovedBroadcast(account, packageNameToNotify, accounts.userId);
849 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700850 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700851 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700852 return true;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800853 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700854 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700855 }
856
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700857 // Update account visibility in cache and database.
858 private boolean updateAccountVisibilityLocked(Account account, String packageName,
859 int newVisibility, UserAccounts accounts) {
860 final long accountId = accounts.accountsDb.findDeAccountId(account);
861 if (accountId < 0) {
862 return false;
863 }
864
865 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
866 try {
867 if (!accounts.accountsDb.setAccountVisibility(accountId, packageName,
868 newVisibility)) {
869 return false;
870 }
871 } finally {
872 StrictMode.setThreadPolicy(oldPolicy);
873 }
874 Map<String, Integer> accountVisibility =
875 getPackagesAndVisibilityForAccountLocked(account, accounts);
876 accountVisibility.put(packageName, newVisibility);
877 return true;
878 }
879
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700880 @Override
881 public void registerAccountListener(String[] accountTypes, String opPackageName) {
882 int callingUid = Binder.getCallingUid();
883 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700884
885 int userId = UserHandle.getCallingUserId();
886 long identityToken = clearCallingIdentity();
887 try {
888 UserAccounts accounts = getUserAccounts(userId);
889 registerAccountListener(accountTypes, opPackageName, accounts);
890 } finally {
891 restoreCallingIdentity(identityToken);
892 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800893 }
894
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700895 private void registerAccountListener(String[] accountTypes, String opPackageName,
896 UserAccounts accounts) {
897 synchronized (accounts.mReceiversForType) {
898 if (accountTypes == null) {
899 // null for any type
900 accountTypes = new String[] {null};
901 }
902 for (String type : accountTypes) {
903 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
904 if (receivers == null) {
905 receivers = new HashMap<>();
906 accounts.mReceiversForType.put(type, receivers);
907 }
908 Integer cnt = receivers.get(opPackageName);
909 receivers.put(opPackageName, cnt != null ? cnt + 1 : 1);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800910 }
911 }
912 }
913
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700914 @Override
915 public void unregisterAccountListener(String[] accountTypes, String opPackageName) {
916 int callingUid = Binder.getCallingUid();
917 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700918 int userId = UserHandle.getCallingUserId();
919 long identityToken = clearCallingIdentity();
920 try {
921 UserAccounts accounts = getUserAccounts(userId);
922 unregisterAccountListener(accountTypes, opPackageName, accounts);
923 } finally {
924 restoreCallingIdentity(identityToken);
925 }
926 }
927
928 private void unregisterAccountListener(String[] accountTypes, String opPackageName,
929 UserAccounts accounts) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700930 synchronized (accounts.mReceiversForType) {
931 if (accountTypes == null) {
932 // null for any type
933 accountTypes = new String[] {null};
934 }
935 for (String type : accountTypes) {
936 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
937 if (receivers == null || receivers.get(opPackageName) == null) {
938 throw new IllegalArgumentException("attempt to unregister wrong receiver");
939 }
940 Integer cnt = receivers.get(opPackageName);
941 if (cnt == 1) {
942 receivers.remove(opPackageName);
943 } else {
944 receivers.put(opPackageName, cnt - 1);
945 }
946 }
947 }
948 }
949
950 // Send notification to all packages which can potentially see the account
951 private void sendNotificationAccountUpdated(Account account, UserAccounts accounts) {
952 Map<String, Integer> packagesToVisibility = getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700953
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700954 for (Entry<String, Integer> packageToVisibility : packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700955 if ((packageToVisibility.getValue() != AccountManager.VISIBILITY_NOT_VISIBLE)
956 && (packageToVisibility.getValue()
957 != AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE)) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700958 notifyPackage(packageToVisibility.getKey(), accounts);
959 }
960 }
961 }
962
963 /**
964 * Sends a direct intent to a package, notifying it of account visibility change.
965 *
966 * @param packageName to send Account to
967 * @param accounts UserAccount that currently hosts the account
968 */
969 private void notifyPackage(String packageName, UserAccounts accounts) {
970 Intent intent = new Intent(AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED);
971 intent.setPackage(packageName);
972 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
973 mContext.sendBroadcastAsUser(intent, new UserHandle(accounts.userId));
974 }
975
976 // Returns a map from package name to visibility, for packages subscribed
977 // to notifications about any account type, or type of provided account
978 // account type or all types.
979 private Map<String, Integer> getRequestingPackages(Account account, UserAccounts accounts) {
980 Set<String> packages = new HashSet<>();
981 synchronized (accounts.mReceiversForType) {
982 for (String type : new String[] {account.type, null}) {
983 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
984 if (receivers != null) {
985 packages.addAll(receivers.keySet());
986 }
987 }
988 }
989 Map<String, Integer> result = new HashMap<>();
990 for (String packageName : packages) {
991 result.put(packageName, resolveAccountVisibility(account, packageName, accounts));
992 }
993 return result;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800994 }
995
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700996 // Returns a list of packages listening to ACTION_ACCOUNT_REMOVED able to see the account.
997 private List<String> getAccountRemovedReceivers(Account account, UserAccounts accounts) {
998 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
999 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
1000 List<ResolveInfo> receivers =
1001 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
1002 List<String> result = new ArrayList<>();
1003 if (receivers == null) {
1004 return result;
1005 }
1006 for (ResolveInfo resolveInfo: receivers) {
1007 String packageName = resolveInfo.activityInfo.applicationInfo.packageName;
1008 int visibility = resolveAccountVisibility(account, packageName, accounts);
1009 if (visibility == AccountManager.VISIBILITY_VISIBLE
1010 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
1011 result.add(packageName);
1012 }
1013 }
1014 return result;
1015 }
1016
1017 // Returns true if given package is listening to ACTION_ACCOUNT_REMOVED and can see the account.
1018 private boolean shouldNotifyPackageOnAccountRemoval(Account account,
1019 String packageName, UserAccounts accounts) {
1020 int visibility = resolveAccountVisibility(account, packageName, accounts);
1021 if (visibility != AccountManager.VISIBILITY_VISIBLE
1022 && visibility != AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
1023 return false;
1024 }
1025
1026 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1027 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
1028 intent.setPackage(packageName);
1029 List<ResolveInfo> receivers =
1030 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
1031 return (receivers != null && receivers.size() > 0);
1032 }
1033
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001034 private boolean packageExistsForUser(String packageName, int userId) {
1035 try {
1036 long identityToken = clearCallingIdentity();
1037 try {
1038 mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -07001039 return true;
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001040 } finally {
1041 restoreCallingIdentity(identityToken);
1042 }
1043 } catch (NameNotFoundException e) {
1044 return false;
1045 }
1046 }
1047
1048 /**
1049 * Returns true if packageName is one of special values.
1050 */
1051 private boolean isSpecialPackageKey(String packageName) {
1052 return (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)
1053 || AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName));
1054 }
1055
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001056 private void sendAccountsChangedBroadcast(int userId) {
1057 Log.i(TAG, "the accounts changed, sending broadcast of "
1058 + ACCOUNTS_CHANGED_INTENT.getAction());
1059 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001060 }
1061
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001062 private void sendAccountRemovedBroadcast(Account account, String packageName, int userId) {
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001063 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1064 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001065 intent.setPackage(packageName);
1066 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
1067 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001068 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
1069 }
1070
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001071 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -07001072 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1073 throws RemoteException {
1074 try {
1075 return super.onTransact(code, data, reply, flags);
1076 } catch (RuntimeException e) {
1077 // The account manager only throws security exceptions, so let's
1078 // log all others.
1079 if (!(e instanceof SecurityException)) {
1080 Slog.wtf(TAG, "Account Manager Crash", e);
1081 }
1082 throw e;
1083 }
1084 }
1085
Amith Yamasani258848d2012-08-10 17:06:33 -07001086 private UserManager getUserManager() {
1087 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001088 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -07001089 }
1090 return mUserManager;
1091 }
1092
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001093 /**
1094 * Validate internal set of accounts against installed authenticators for
1095 * given user. Clears cached authenticators before validating.
1096 */
1097 public void validateAccounts(int userId) {
1098 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001099 // Invalidate user-specific cache to make sure we catch any
1100 // removed authenticators.
1101 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
1102 }
1103
1104 /**
1105 * Validate internal set of accounts against installed authenticators for
1106 * given user. Clear cached authenticators before validating when requested.
1107 */
1108 private void validateAccountsInternal(
1109 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001110 if (Log.isLoggable(TAG, Log.DEBUG)) {
1111 Log.d(TAG, "validateAccountsInternal " + accounts.userId
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001112 + " isCeDatabaseAttached=" + accounts.accountsDb.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001113 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001114 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001115
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001116 if (invalidateAuthenticatorCache) {
1117 mAuthenticatorCache.invalidateCache(accounts.userId);
1118 }
1119
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001120 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
1121 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001122 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001123
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001124 synchronized (accounts.dbLock) {
1125 synchronized (accounts.cacheLock) {
1126 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001127
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001128 // Get a map of stored authenticator types to UID
1129 final AccountsDb accountsDb = accounts.accountsDb;
1130 Map<String, Integer> metaAuthUid = accountsDb.findMetaAuthUid();
1131 // Create a list of authenticator type whose previous uid no longer exists
1132 HashSet<String> obsoleteAuthType = Sets.newHashSet();
1133 SparseBooleanArray knownUids = null;
1134 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
1135 String type = authToUidEntry.getKey();
1136 int uid = authToUidEntry.getValue();
1137 Integer knownUid = knownAuth.get(type);
1138 if (knownUid != null && uid == knownUid) {
1139 // Remove it from the knownAuth list if it's unchanged.
1140 knownAuth.remove(type);
1141 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001142 /*
1143 * The authenticator is presently not cached and should only be triggered
1144 * when we think an authenticator has been removed (or is being updated).
1145 * But we still want to check if any data with the associated uid is
1146 * around. This is an (imperfect) signal that the package may be updating.
1147 *
1148 * A side effect of this is that an authenticator sharing a uid with
1149 * multiple apps won't get its credentials wiped as long as some app with
1150 * that uid is still on the device. But I suspect that this is a rare case.
1151 * And it isn't clear to me how an attacker could really exploit that
1152 * feature.
1153 *
1154 * The upshot is that we don't have to worry about accounts getting
1155 * uninstalled while the authenticator's package is being updated.
1156 *
1157 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001158 if (knownUids == null) {
1159 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
1160 }
1161 if (!knownUids.get(uid)) {
1162 // The authenticator is not presently available to the cache. And the
1163 // package no longer has a data directory (so we surmise it isn't
1164 // updating). So purge its data from the account databases.
1165 obsoleteAuthType.add(type);
1166 // And delete it from the TABLE_META
1167 accountsDb.deleteMetaByAuthTypeAndUid(type, uid);
1168 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001169 }
1170 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001171
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001172 // Add the newly registered authenticator to TABLE_META. If old authenticators have
1173 // been re-enabled (after being updated for example), then we just overwrite the old
1174 // values.
1175 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1176 accountsDb.insertOrReplaceMetaAuthTypeAndUid(entry.getKey(), entry.getValue());
1177 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001178
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001179 final Map<Long, Account> accountsMap = accountsDb.findAllDeAccounts();
1180 try {
1181 accounts.accountCache.clear();
1182 final HashMap<String, ArrayList<String>> accountNamesByType
1183 = new LinkedHashMap<>();
1184 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1185 final long accountId = accountEntry.getKey();
1186 final Account account = accountEntry.getValue();
1187 if (obsoleteAuthType.contains(account.type)) {
1188 Slog.w(TAG, "deleting account " + account.name + " because type "
1189 + account.type
1190 + "'s registered authenticator no longer exist.");
1191 Map<String, Integer> packagesToVisibility =
1192 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001193 List<String> accountRemovedReceivers =
1194 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001195 accountsDb.beginTransaction();
1196 try {
1197 accountsDb.deleteDeAccount(accountId);
1198 // Also delete from CE table if user is unlocked; if user is
1199 // currently locked the account will be removed later by
1200 // syncDeCeAccountsLocked
1201 if (userUnlocked) {
1202 accountsDb.deleteCeAccount(accountId);
1203 }
1204 accountsDb.setTransactionSuccessful();
1205 } finally {
1206 accountsDb.endTransaction();
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001207 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001208 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001209
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001210 logRecord(AccountsDb.DEBUG_ACTION_AUTHENTICATOR_REMOVE,
1211 AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001212
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001213 accounts.userDataCache.remove(account);
1214 accounts.authTokenCache.remove(account);
1215 accounts.accountTokenCaches.remove(account);
1216 accounts.visibilityCache.remove(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001217
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001218 for (Entry<String, Integer> packageToVisibility :
1219 packagesToVisibility.entrySet()) {
sunjian066aa5e2017-06-05 12:16:59 -07001220 if (isVisible(packageToVisibility.getValue())) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001221 notifyPackage(packageToVisibility.getKey(), accounts);
1222 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001223 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001224 for (String packageName : accountRemovedReceivers) {
1225 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
1226 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001227 } else {
1228 ArrayList<String> accountNames = accountNamesByType.get(account.type);
1229 if (accountNames == null) {
1230 accountNames = new ArrayList<>();
1231 accountNamesByType.put(account.type, accountNames);
1232 }
1233 accountNames.add(account.name);
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001234 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001235 }
1236 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
1237 final String accountType = cur.getKey();
1238 final ArrayList<String> accountNames = cur.getValue();
1239 final Account[] accountsForType = new Account[accountNames.size()];
1240 for (int i = 0; i < accountsForType.length; i++) {
1241 accountsForType[i] = new Account(accountNames.get(i), accountType,
1242 UUID.randomUUID().toString());
Fred Quintana56285a62010-12-02 14:20:51 -08001243 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001244 accounts.accountCache.put(accountType, accountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08001245 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001246 accounts.visibilityCache.putAll(accountsDb.findAllVisibilityValues());
1247 } finally {
1248 if (accountDeleted) {
1249 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintana56285a62010-12-02 14:20:51 -08001250 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001251 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001252 }
1253 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001254 }
1255
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001256 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1257 // Get the UIDs of all apps that might have data on the device. We want
1258 // to preserve user data if the app might otherwise be storing data.
1259 List<PackageInfo> pkgsWithData =
1260 mPackageManager.getInstalledPackagesAsUser(
1261 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1262 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1263 for (PackageInfo pkgInfo : pkgsWithData) {
1264 if (pkgInfo.applicationInfo != null
1265 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1266 knownUids.put(pkgInfo.applicationInfo.uid, true);
1267 }
1268 }
1269 return knownUids;
1270 }
1271
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001272 static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001273 Context context,
1274 int userId) {
1275 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001276 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1277 }
1278
1279 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1280 IAccountAuthenticatorCache authCache,
1281 int userId) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08001282 HashMap<String, Integer> knownAuth = new LinkedHashMap<>();
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001283 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1284 .getAllServices(userId)) {
1285 knownAuth.put(service.type.type, service.uid);
1286 }
1287 return knownAuth;
1288 }
1289
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001291 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 }
1293
1294 protected UserAccounts getUserAccounts(int userId) {
1295 synchronized (mUsers) {
1296 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001297 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001298 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001299 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1300 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001301 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001302 initializeDebugDbSizeAndCompileSqlStatementForLogging(accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001303 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001304 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001305 validateAccounts = true;
1306 }
1307 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001308 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001309 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001310 synchronized (accounts.dbLock) {
1311 synchronized (accounts.cacheLock) {
1312 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1313 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1314 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001315 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001316 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001317 }
1318 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001319 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001320 }
1321 return accounts;
1322 }
1323 }
1324
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001325 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1326 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001327 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001328 if (!accountsToRemove.isEmpty()) {
1329 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1330 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001331 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1332 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001333
1334 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001335 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001336 }
1337 }
1338 }
1339
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001340 private void purgeOldGrantsAll() {
1341 synchronized (mUsers) {
1342 for (int i = 0; i < mUsers.size(); i++) {
1343 purgeOldGrants(mUsers.valueAt(i));
1344 }
1345 }
1346 }
1347
1348 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001349 synchronized (accounts.dbLock) {
1350 synchronized (accounts.cacheLock) {
1351 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1352 for (int uid : uids) {
1353 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1354 if (packageExists) {
1355 continue;
1356 }
1357 Log.d(TAG, "deleting grants for UID " + uid
1358 + " because its package is no longer installed");
1359 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001360 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001361 }
1362 }
1363 }
1364
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001365 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001366 if (isSpecialPackageKey(packageName)) {
1367 return;
1368 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001369 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001370 int numberOfUsers = mUsers.size();
1371 for (int i = 0; i < numberOfUsers; i++) {
1372 UserAccounts accounts = mUsers.valueAt(i);
1373 try {
1374 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1375 } catch (NameNotFoundException e) {
1376 // package does not exist - remove visibility values
1377 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001378 synchronized (accounts.dbLock) {
1379 synchronized (accounts.cacheLock) {
1380 for (Account account : accounts.visibilityCache.keySet()) {
1381 Map<String, Integer> accountVisibility =
1382 getPackagesAndVisibilityForAccountLocked(account, accounts);
1383 accountVisibility.remove(packageName);
1384 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001385 }
1386 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001387 }
1388 }
1389 }
1390 }
1391
Fyodor Kupolov945c97e2017-06-21 17:45:19 -07001392 private void purgeUserData(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001393 UserAccounts accounts;
1394 synchronized (mUsers) {
1395 accounts = mUsers.get(userId);
1396 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001397 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001398 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001399 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001400 synchronized (accounts.dbLock) {
1401 synchronized (accounts.cacheLock) {
Fyodor Kupolov56e158f2017-05-23 16:41:51 -07001402 accounts.statementForLogging.close();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001403 accounts.accountsDb.close();
1404 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001405 }
Amith Yamasani13593602012-03-22 16:16:17 -07001406 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001407 }
1408
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001409 @VisibleForTesting
1410 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001411 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1412 }
1413
1414 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001415 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1416 Log.v(TAG, "onUserUnlocked " + userId);
1417 }
1418 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001419 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001420 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001421 if (userId < 1) return;
Fyodor Kupolov2bc895d2017-12-19 11:53:47 -08001422 mHandler.post(() -> syncSharedAccounts(userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001423 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001424
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001425 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001426 // Check if there's a shared account that needs to be created as an account
1427 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1428 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001429 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001430 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001431 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001432 : UserHandle.USER_SYSTEM;
1433 if (parentUserId < 0) {
1434 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1435 return;
1436 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001437 for (Account sa : sharedAccounts) {
1438 if (ArrayUtils.contains(accounts, sa)) continue;
1439 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001440 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001441 }
1442 }
1443
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001444 @Override
1445 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001446 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001447 }
1448
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001449 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001450 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001451 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001452 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1453 Log.v(TAG, "getPassword: " + account
1454 + ", caller's uid " + Binder.getCallingUid()
1455 + ", pid " + Binder.getCallingPid());
1456 }
Fred Quintana382601f2010-03-25 12:25:10 -07001457 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001458 int userId = UserHandle.getCallingUserId();
1459 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001460 String msg = String.format(
1461 "uid %s cannot get secrets for accounts of type: %s",
1462 callingUid,
1463 account.type);
1464 throw new SecurityException(msg);
1465 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001466 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001467 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001468 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001469 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001470 } finally {
1471 restoreCallingIdentity(identityToken);
1472 }
1473 }
1474
Amith Yamasani04e0d262012-02-14 11:50:53 -08001475 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001476 if (account == null) {
1477 return null;
1478 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001479 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001480 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1481 return null;
1482 }
Fred Quintana31957f12009-10-21 13:43:10 -07001483
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001484 synchronized (accounts.dbLock) {
1485 synchronized (accounts.cacheLock) {
1486 return accounts.accountsDb
1487 .findAccountPasswordByNameAndType(account.name, account.type);
1488 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001489 }
1490 }
1491
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001492 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001493 public String getPreviousName(Account account) {
1494 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1495 Log.v(TAG, "getPreviousName: " + account
1496 + ", caller's uid " + Binder.getCallingUid()
1497 + ", pid " + Binder.getCallingPid());
1498 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001499 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001500 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001501 long identityToken = clearCallingIdentity();
1502 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001503 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001504 return readPreviousNameInternal(accounts, account);
1505 } finally {
1506 restoreCallingIdentity(identityToken);
1507 }
1508 }
1509
1510 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1511 if (account == null) {
1512 return null;
1513 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001514 synchronized (accounts.dbLock) {
1515 synchronized (accounts.cacheLock) {
1516 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1517 if (previousNameRef == null) {
1518 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1519 previousNameRef = new AtomicReference<>(previousName);
1520 accounts.previousNameCache.put(account, previousNameRef);
1521 return previousName;
1522 } else {
1523 return previousNameRef.get();
1524 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001525 }
1526 }
1527 }
1528
1529 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001530 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001531 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001532 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001533 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1534 account, key, callingUid, Binder.getCallingPid());
1535 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001536 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001537 Preconditions.checkNotNull(account, "account cannot be null");
1538 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001539 int userId = UserHandle.getCallingUserId();
1540 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001541 String msg = String.format(
1542 "uid %s cannot get user data for accounts of type: %s",
1543 callingUid,
1544 account.type);
1545 throw new SecurityException(msg);
1546 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001547 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001548 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1549 return null;
1550 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001551 long identityToken = clearCallingIdentity();
1552 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001553 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001554 if (!accountExistsCache(accounts, account)) {
1555 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001556 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001557 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001558 } finally {
1559 restoreCallingIdentity(identityToken);
1560 }
1561 }
1562
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001563 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001564 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001565 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001566 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1567 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001568 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001569 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001570 + ", pid " + Binder.getCallingPid());
1571 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001572 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001573 if (isCrossUser(callingUid, userId)) {
1574 throw new SecurityException(
1575 String.format(
1576 "User %s tying to get authenticator types for %s" ,
1577 UserHandle.getCallingUserId(),
1578 userId));
1579 }
1580
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001581 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001582 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001583 return getAuthenticatorTypesInternal(userId);
1584
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001585 } finally {
1586 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001587 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001588 }
1589
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001590 /**
1591 * Should only be called inside of a clearCallingIdentity block.
1592 */
1593 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001594 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001595 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1596 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1597 AuthenticatorDescription[] types =
1598 new AuthenticatorDescription[authenticatorCollection.size()];
1599 int i = 0;
1600 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1601 : authenticatorCollection) {
1602 types[i] = authenticator.type;
1603 i++;
1604 }
1605 return types;
1606 }
1607
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001608 private boolean isCrossUser(int callingUid, int userId) {
1609 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001610 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001611 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001612 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1613 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001614 }
1615
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001616 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001617 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001618 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001619 }
1620
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001621 @Override
1622 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001623 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001624 int callingUid = Binder.getCallingUid();
1625 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1626 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001627 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001628 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001629 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1630 final UserAccounts toAccounts = getUserAccounts(userTo);
1631 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001632 if (response != null) {
1633 Bundle result = new Bundle();
1634 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1635 try {
1636 response.onResult(result);
1637 } catch (RemoteException e) {
1638 Slog.w(TAG, "Failed to report error back to the client." + e);
1639 }
1640 }
1641 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001642 }
1643
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001644 Slog.d(TAG, "Copying account " + account.name
1645 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001646 long identityToken = clearCallingIdentity();
1647 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001648 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001649 false /* stripAuthTokenFromResult */, account.name,
1650 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001651 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001652 protected String toDebugString(long now) {
1653 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1654 + ", " + account.type;
1655 }
1656
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001657 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001658 public void run() throws RemoteException {
1659 mAuthenticator.getAccountCredentialsForCloning(this, account);
1660 }
1661
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001662 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001663 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001664 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001665 if (result != null
1666 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1667 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001668 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001669 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001670 super.onResult(result);
1671 }
1672 }
1673 }.bind();
1674 } finally {
1675 restoreCallingIdentity(identityToken);
1676 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001677 }
1678
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001679 @Override
1680 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001681 final int callingUid = Binder.getCallingUid();
1682 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1683 String msg = String.format(
1684 "accountAuthenticated( account: %s, callerUid: %s)",
1685 account,
1686 callingUid);
1687 Log.v(TAG, msg);
1688 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001689 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001690 int userId = UserHandle.getCallingUserId();
1691 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001692 String msg = String.format(
1693 "uid %s cannot notify authentication for accounts of type: %s",
1694 callingUid,
1695 account.type);
1696 throw new SecurityException(msg);
1697 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001698
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001699 if (!canUserModifyAccounts(userId, callingUid) ||
1700 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001701 return false;
1702 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001703
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001704 long identityToken = clearCallingIdentity();
1705 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001706 UserAccounts accounts = getUserAccounts(userId);
1707 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001708 } finally {
1709 restoreCallingIdentity(identityToken);
1710 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001711 }
1712
1713 private boolean updateLastAuthenticatedTime(Account account) {
1714 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001715 synchronized (accounts.dbLock) {
1716 synchronized (accounts.cacheLock) {
1717 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1718 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001719 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001720 }
1721
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001722 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001723 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1724 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001725 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001726 long id = clearCallingIdentity();
1727 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001728 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001729 false /* stripAuthTokenFromResult */, account.name,
1730 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001731 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001732 protected String toDebugString(long now) {
1733 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1734 + ", " + account.type;
1735 }
1736
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001737 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001738 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001739 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov16bedd42017-03-30 10:00:49 -07001740 for (Account acc : getAccounts(parentUserId, mContext.getOpPackageName())) {
1741 if (acc.equals(account)) {
1742 mAuthenticator.addAccountFromCredentials(
1743 this, account, accountCredentials);
1744 break;
Amith Yamasani5be347b2013-03-31 17:44:31 -07001745 }
1746 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001747 }
1748
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001749 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001750 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001751 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001752 // TODO: Anything to do if if succedded?
1753 // TODO: If it failed: Show error notification? Should we remove the shadow
1754 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001755 // TODO: what we do with the visibility?
1756
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001757 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001758 }
1759
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001760 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001761 public void onError(int errorCode, String errorMessage) {
1762 super.onError(errorCode, errorMessage);
1763 // TODO: Show error notification to user
1764 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1765 }
1766
1767 }.bind();
1768 } finally {
1769 restoreCallingIdentity(id);
1770 }
1771 }
1772
Amith Yamasani04e0d262012-02-14 11:50:53 -08001773 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001774 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001775 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001776 if (account == null) {
1777 return false;
1778 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001779 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001780 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1781 + " is locked. callingUid=" + callingUid);
1782 return false;
1783 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001784 synchronized (accounts.dbLock) {
1785 synchronized (accounts.cacheLock) {
1786 accounts.accountsDb.beginTransaction();
1787 try {
1788 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
1789 Log.w(TAG, "insertAccountIntoDatabase: " + account
1790 + ", skipping since the account already exists");
1791 return false;
1792 }
1793 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1794 if (accountId < 0) {
1795 Log.w(TAG, "insertAccountIntoDatabase: " + account
1796 + ", skipping the DB insert failed");
1797 return false;
1798 }
1799 // Insert into DE table
1800 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
1801 Log.w(TAG, "insertAccountIntoDatabase: " + account
1802 + ", skipping the DB insert failed");
1803 return false;
1804 }
1805 if (extras != null) {
1806 for (String key : extras.keySet()) {
1807 final String value = extras.getString(key);
1808 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
1809 Log.w(TAG, "insertAccountIntoDatabase: " + account
1810 + ", skipping since insertExtra failed for key " + key);
1811 return false;
1812 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001813 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001814 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001815
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001816 if (packageToVisibility != null) {
1817 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1818 setAccountVisibility(account, entry.getKey() /* package */,
1819 entry.getValue() /* visibility */, false /* notify */,
1820 accounts);
1821 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001822 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001823 accounts.accountsDb.setTransactionSuccessful();
1824
1825 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1826 accountId,
1827 accounts, callingUid);
1828
1829 insertAccountIntoCacheLocked(accounts, account);
1830 } finally {
1831 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001832 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001833 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001834 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001835 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1836 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001837 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001838
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001839 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001840 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1841 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001842
Amith Yamasani5be347b2013-03-31 17:44:31 -07001843 return true;
1844 }
1845
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001846 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001847 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001848 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001849 }
1850 }
1851
Amith Yamasani5be347b2013-03-31 17:44:31 -07001852 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001853 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001854 * running, then clone the account too.
1855 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001856 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001857 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001858 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001859 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001860 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001861 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001862 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001863 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001864 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001865 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001866 }
1867 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001868 }
1869 }
1870
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001871 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001872 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001873 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001874 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001875 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001876 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1877 Log.v(TAG, "hasFeatures: " + account
1878 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001879 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001880 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001881 + ", pid " + Binder.getCallingPid());
1882 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001883 Preconditions.checkArgument(account != null, "account cannot be null");
1884 Preconditions.checkArgument(response != null, "response cannot be null");
1885 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001886 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001887 checkReadAccountsPermitted(callingUid, account.type, userId,
1888 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001889
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001890 long identityToken = clearCallingIdentity();
1891 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001892 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001893 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001894 } finally {
1895 restoreCallingIdentity(identityToken);
1896 }
1897 }
1898
1899 private class TestFeaturesSession extends Session {
1900 private final String[] mFeatures;
1901 private final Account mAccount;
1902
Amith Yamasani04e0d262012-02-14 11:50:53 -08001903 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001904 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001905 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001906 true /* stripAuthTokenFromResult */, account.name,
1907 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001908 mFeatures = features;
1909 mAccount = account;
1910 }
1911
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001912 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001913 public void run() throws RemoteException {
1914 try {
1915 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1916 } catch (RemoteException e) {
1917 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1918 }
1919 }
1920
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001921 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001922 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001923 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001924 IAccountManagerResponse response = getResponseAndClose();
1925 if (response != null) {
1926 try {
1927 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001928 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001929 return;
1930 }
Fred Quintana56285a62010-12-02 14:20:51 -08001931 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1932 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1933 + response);
1934 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001935 final Bundle newResult = new Bundle();
1936 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1937 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1938 response.onResult(newResult);
1939 } catch (RemoteException e) {
1940 // if the caller is dead then there is no one to care about remote exceptions
1941 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1942 Log.v(TAG, "failure while notifying response", e);
1943 }
1944 }
1945 }
1946 }
1947
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001948 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001949 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001950 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001951 + ", " + mAccount
1952 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1953 }
1954 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001955
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001956 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001957 public void renameAccount(
1958 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001959 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001960 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1961 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001962 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001963 + ", pid " + Binder.getCallingPid());
1964 }
1965 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001966 int userId = UserHandle.getCallingUserId();
1967 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001968 String msg = String.format(
1969 "uid %s cannot rename accounts of type: %s",
1970 callingUid,
1971 accountToRename.type);
1972 throw new SecurityException(msg);
1973 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001974 long identityToken = clearCallingIdentity();
1975 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001976 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001977 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001978 Bundle result = new Bundle();
1979 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1980 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001981 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
1982 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001983 try {
1984 response.onResult(result);
1985 } catch (RemoteException e) {
1986 Log.w(TAG, e.getMessage());
1987 }
1988 } finally {
1989 restoreCallingIdentity(identityToken);
1990 }
1991 }
1992
1993 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001994 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001995 Account resultAccount = null;
1996 /*
1997 * Cancel existing notifications. Let authenticators
1998 * re-post notifications as required. But we don't know if
1999 * the authenticators have bound their notifications to
2000 * now stale account name data.
2001 *
2002 * With a rename api, we might not need to do this anymore but it
2003 * shouldn't hurt.
2004 */
2005 cancelNotification(
2006 getSigninRequiredNotificationId(accounts, accountToRename),
Chris Wren717a8812017-03-31 15:34:39 -04002007 new UserHandle(accounts.userId));
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002008 synchronized(accounts.credentialsPermissionNotificationIds) {
2009 for (Pair<Pair<Account, String>, Integer> pair:
2010 accounts.credentialsPermissionNotificationIds.keySet()) {
2011 if (accountToRename.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002012 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002013 cancelNotification(id, new UserHandle(accounts.userId));
2014 }
2015 }
2016 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002017 synchronized (accounts.dbLock) {
2018 synchronized (accounts.cacheLock) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002019 List<String> accountRemovedReceivers =
2020 getAccountRemovedReceivers(accountToRename, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002021 accounts.accountsDb.beginTransaction();
2022 Account renamedAccount = new Account(newName, accountToRename.type);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002023 try {
chengangf2d081c2017-12-27 17:17:32 +08002024 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
2025 Log.e(TAG, "renameAccount failed - account with new name already exists");
2026 return null;
2027 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002028 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
2029 if (accountId >= 0) {
2030 accounts.accountsDb.renameCeAccount(accountId, newName);
2031 if (accounts.accountsDb.renameDeAccount(
2032 accountId, newName, accountToRename.name)) {
2033 accounts.accountsDb.setTransactionSuccessful();
2034 } else {
2035 Log.e(TAG, "renameAccount failed");
2036 return null;
2037 }
2038 } else {
2039 Log.e(TAG, "renameAccount failed - old account does not exist");
2040 return null;
2041 }
2042 } finally {
2043 accounts.accountsDb.endTransaction();
2044 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002045 /*
2046 * Database transaction was successful. Clean up cached
2047 * data associated with the account in the user profile.
2048 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002049 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002050 /*
2051 * Extract the data and token caches before removing the
2052 * old account to preserve the user data associated with
2053 * the account.
2054 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002055 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
2056 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
2057 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
2058 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002059 /*
2060 * Update the cached data associated with the renamed
2061 * account.
2062 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002063 accounts.userDataCache.put(renamedAccount, tmpData);
2064 accounts.authTokenCache.put(renamedAccount, tmpTokens);
2065 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
2066 accounts.previousNameCache.put(
2067 renamedAccount,
2068 new AtomicReference<>(accountToRename.name));
2069 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002070
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002071 int parentUserId = accounts.userId;
2072 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002073 /*
2074 * Owner or system user account was renamed, rename the account for
2075 * those users with which the account was shared.
2076 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002077 List<UserInfo> users = getUserManager().getUsers(true);
2078 for (UserInfo user : users) {
2079 if (user.isRestricted()
2080 && (user.restrictedProfileParentId == parentUserId)) {
2081 renameSharedAccountAsUser(accountToRename, newName, user.id);
2082 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002083 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002084 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002085
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002086 sendNotificationAccountUpdated(resultAccount, accounts);
2087 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002088 for (String packageName : accountRemovedReceivers) {
2089 sendAccountRemovedBroadcast(accountToRename, packageName, accounts.userId);
2090 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002091 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002092 }
2093 return resultAccount;
2094 }
2095
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002096 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002097 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002098 return userInfo != null && userInfo.canHaveProfile();
2099 }
2100
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002101 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002102 public void removeAccount(IAccountManagerResponse response, Account account,
2103 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002104 removeAccountAsUser(
2105 response,
2106 account,
2107 expectActivityLaunch,
2108 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002109 }
2110
2111 @Override
2112 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002113 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002114 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002115 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2116 Log.v(TAG, "removeAccount: " + account
2117 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002118 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002119 + ", pid " + Binder.getCallingPid()
2120 + ", for user id " + userId);
2121 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002122 Preconditions.checkArgument(account != null, "account cannot be null");
2123 Preconditions.checkArgument(response != null, "response cannot be null");
2124
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002125 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002126 if (isCrossUser(callingUid, userId)) {
2127 throw new SecurityException(
2128 String.format(
2129 "User %s tying remove account for %s" ,
2130 UserHandle.getCallingUserId(),
2131 userId));
2132 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002133 /*
Alex Chauf788f9c2017-12-08 15:16:46 +00002134 * Only the system, authenticator or profile owner should be allowed to remove accounts for
2135 * that authenticator. This will let users remove accounts (via Settings in the system) but
2136 * not arbitrary applications (like competing authenticators).
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002137 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002138 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00002139 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
Alex Chauf788f9c2017-12-08 15:16:46 +00002140 && !isSystemUid(callingUid)
2141 && !isProfileOwner(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002142 String msg = String.format(
2143 "uid %s cannot remove accounts of type: %s",
2144 callingUid,
2145 account.type);
2146 throw new SecurityException(msg);
2147 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002148 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002149 try {
2150 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2151 "User cannot modify accounts");
2152 } catch (RemoteException re) {
2153 }
2154 return;
2155 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002156 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002157 try {
2158 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2159 "User cannot modify accounts of this type (policy).");
2160 } catch (RemoteException re) {
2161 }
2162 return;
2163 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002164 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002165 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002166 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002167 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002168 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002169 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002170 if (account.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002171 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002172 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002173 }
2174 }
2175 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002176 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002177 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002178 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2179 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002180 accountId,
2181 accounts,
2182 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002183 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002184 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2185 } finally {
2186 restoreCallingIdentity(identityToken);
2187 }
2188 }
2189
2190 @Override
2191 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002192 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002193 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2194 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002195 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002196 + ", pid " + Binder.getCallingPid());
2197 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002198 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002199 if (account == null) {
2200 /*
2201 * Null accounts should result in returning false, as per
2202 * AccountManage.addAccountExplicitly(...) java doc.
2203 */
2204 Log.e(TAG, "account is null");
2205 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002206 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002207 String msg = String.format(
Brandon Weeks9e4e96d2017-08-24 15:24:16 -07002208 "uid %s cannot explicitly remove accounts of type: %s",
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002209 callingUid,
2210 account.type);
2211 throw new SecurityException(msg);
2212 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002213 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002214 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002215 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002216 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2217 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002218 accountId,
2219 accounts,
2220 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002221 long identityToken = clearCallingIdentity();
2222 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002223 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002224 } finally {
2225 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002226 }
Fred Quintana60307342009-03-24 22:48:12 -07002227 }
2228
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002229 private class RemoveAccountSession extends Session {
2230 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002231 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002232 Account account, boolean expectActivityLaunch) {
2233 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002234 true /* stripAuthTokenFromResult */, account.name,
2235 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002236 mAccount = account;
2237 }
2238
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002239 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002240 protected String toDebugString(long now) {
2241 return super.toDebugString(now) + ", removeAccount"
2242 + ", account " + mAccount;
2243 }
2244
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002245 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002246 public void run() throws RemoteException {
2247 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2248 }
2249
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002250 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002251 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002252 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002253 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2254 && !result.containsKey(AccountManager.KEY_INTENT)) {
2255 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002256 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002257 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002258 }
2259 IAccountManagerResponse response = getResponseAndClose();
2260 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2262 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2263 + response);
2264 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002265 try {
tiansiming5330b5a2017-10-13 10:57:25 +08002266 response.onResult(result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002267 } catch (RemoteException e) {
tiansiming5330b5a2017-10-13 10:57:25 +08002268 Slog.e(TAG, "Error calling onResult()", e);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002269 }
2270 }
2271 }
2272 super.onResult(result);
2273 }
2274 }
2275
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002276 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002277 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002278 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002279 }
2280
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002281 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002282 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002283 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002284 if (!userUnlocked) {
2285 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2286 + " is still locked. CE data will be removed later");
2287 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002288 synchronized (accounts.dbLock) {
2289 synchronized (accounts.cacheLock) {
2290 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2291 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002292 List<String> accountRemovedReceivers =
2293 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002294 accounts.accountsDb.beginTransaction();
2295 // Set to a dummy value, this will only be used if the database
2296 // transaction succeeds.
2297 long accountId = -1;
2298 try {
2299 accountId = accounts.accountsDb.findDeAccountId(account);
2300 if (accountId >= 0) {
2301 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002302 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002303 // always delete from CE table if CE storage is available
2304 // DE account could be removed while CE was locked
2305 if (userUnlocked) {
2306 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2307 if (ceAccountId >= 0) {
2308 accounts.accountsDb.deleteCeAccount(ceAccountId);
2309 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002310 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002311 accounts.accountsDb.setTransactionSuccessful();
2312 } finally {
2313 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002314 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002315 if (isChanged) {
2316 removeAccountFromCacheLocked(accounts, account);
2317 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2318 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002319 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2320 || (packageToVisibility.getValue()
2321 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002322 notifyPackage(packageToVisibility.getKey(), accounts);
2323 }
2324 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002325
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002326 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2327 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002328 for (String packageName : accountRemovedReceivers) {
2329 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2330 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002331 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2332 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2333 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2334 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002335 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002336 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002337 long id = Binder.clearCallingIdentity();
2338 try {
2339 int parentUserId = accounts.userId;
2340 if (canHaveProfile(parentUserId)) {
2341 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002342 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002343 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002344 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002345 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002346 }
2347 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002348 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002349 } finally {
2350 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002351 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002352
2353 if (isChanged) {
2354 synchronized (accounts.credentialsPermissionNotificationIds) {
2355 for (Pair<Pair<Account, String>, Integer> key
2356 : accounts.credentialsPermissionNotificationIds.keySet()) {
2357 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002358 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002359 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002360 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002361 account, uid, false));
2362 }
2363 }
2364 }
2365 }
2366
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002367 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002368 }
2369
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002370 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002371 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002372 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002373 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2374 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002375 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2376 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002377 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002378 + ", pid " + Binder.getCallingPid());
2379 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002380 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002381 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002382 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002383 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002384 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002385 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002386 accounts.accountsDb.beginTransaction();
2387 try {
2388 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2389 accounts.accountsDb.setTransactionSuccessful();
2390 } finally {
2391 accounts.accountsDb.endTransaction();
2392 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002393 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002394 for (Pair<Account, String> tokenInfo : deletedTokens) {
2395 Account act = tokenInfo.first;
2396 String tokenType = tokenInfo.second;
2397 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002398 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002399 // wipe out cached token in memory.
2400 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002401 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002402 }
Fred Quintana60307342009-03-24 22:48:12 -07002403 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002404 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002405 }
2406 }
2407
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002408 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002409 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002410 // TODO Move to AccountsDB
2411 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002412 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002413
Fred Quintana33269202009-04-20 16:05:10 -07002414 try {
2415 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002416 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002417 String accountName = cursor.getString(1);
2418 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002419 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002420 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002421 }
Fred Quintana33269202009-04-20 16:05:10 -07002422 } finally {
2423 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002424 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002425 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002426 }
2427
Carlos Valdivia91979be2015-05-22 14:11:35 -07002428 private void saveCachedToken(
2429 UserAccounts accounts,
2430 Account account,
2431 String callerPkg,
2432 byte[] callerSigDigest,
2433 String tokenType,
2434 String token,
2435 long expiryMillis) {
2436
2437 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2438 return;
2439 }
2440 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002441 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002442 synchronized (accounts.cacheLock) {
2443 accounts.accountTokenCaches.put(
2444 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002445 }
2446 }
2447
Amith Yamasani04e0d262012-02-14 11:50:53 -08002448 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2449 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002450 if (account == null || type == null) {
2451 return false;
2452 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002453 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002454 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002455 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002456 accounts.accountsDb.beginTransaction();
2457 boolean updateCache = false;
2458 try {
2459 long accountId = accounts.accountsDb.findDeAccountId(account);
2460 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002461 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002462 }
2463 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2464 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2465 accounts.accountsDb.setTransactionSuccessful();
2466 updateCache = true;
2467 return true;
2468 }
2469 return false;
2470 } finally {
2471 accounts.accountsDb.endTransaction();
2472 if (updateCache) {
2473 synchronized (accounts.cacheLock) {
2474 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2475 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002476 }
Fred Quintana33269202009-04-20 16:05:10 -07002477 }
Fred Quintana60307342009-03-24 22:48:12 -07002478 }
2479 }
2480
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002481 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002482 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002483 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002484 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2485 Log.v(TAG, "peekAuthToken: " + account
2486 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002487 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002488 + ", pid " + Binder.getCallingPid());
2489 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002490 Preconditions.checkNotNull(account, "account cannot be null");
2491 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002492 int userId = UserHandle.getCallingUserId();
2493 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002494 String msg = String.format(
2495 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2496 callingUid,
2497 account.type);
2498 throw new SecurityException(msg);
2499 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002500 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002501 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2502 + callingUid);
2503 return null;
2504 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002505 long identityToken = clearCallingIdentity();
2506 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002507 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002508 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002509 } finally {
2510 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002511 }
Fred Quintana60307342009-03-24 22:48:12 -07002512 }
2513
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002514 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002515 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002516 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002517 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2518 Log.v(TAG, "setAuthToken: " + account
2519 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002520 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002521 + ", pid " + Binder.getCallingPid());
2522 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002523 Preconditions.checkNotNull(account, "account cannot be null");
2524 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002525 int userId = UserHandle.getCallingUserId();
2526 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002527 String msg = String.format(
2528 "uid %s cannot set auth tokens associated with accounts of type: %s",
2529 callingUid,
2530 account.type);
2531 throw new SecurityException(msg);
2532 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002533 long identityToken = clearCallingIdentity();
2534 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002535 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002536 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002537 } finally {
2538 restoreCallingIdentity(identityToken);
2539 }
Fred Quintana60307342009-03-24 22:48:12 -07002540 }
2541
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002542 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002543 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002544 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002545 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2546 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002547 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002548 + ", pid " + Binder.getCallingPid());
2549 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002550 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002551 int userId = UserHandle.getCallingUserId();
2552 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002553 String msg = String.format(
2554 "uid %s cannot set secrets for accounts of type: %s",
2555 callingUid,
2556 account.type);
2557 throw new SecurityException(msg);
2558 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002559 long identityToken = clearCallingIdentity();
2560 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002561 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002562 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002563 } finally {
2564 restoreCallingIdentity(identityToken);
2565 }
Fred Quintana60307342009-03-24 22:48:12 -07002566 }
2567
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002568 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2569 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002570 if (account == null) {
2571 return;
2572 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002573 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002574 synchronized (accounts.dbLock) {
2575 synchronized (accounts.cacheLock) {
2576 accounts.accountsDb.beginTransaction();
2577 try {
2578 final long accountId = accounts.accountsDb.findDeAccountId(account);
2579 if (accountId >= 0) {
2580 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2581 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2582 accounts.authTokenCache.remove(account);
2583 accounts.accountTokenCaches.remove(account);
2584 accounts.accountsDb.setTransactionSuccessful();
2585 // If there is an account whose password will be updated and the database
2586 // transactions succeed, then we say that a change has occured. Even if the
2587 // new password is the same as the old and there were no authtokens to
2588 // delete.
2589 isChanged = true;
2590 String action = (password == null || password.length() == 0) ?
2591 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2592 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2593 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2594 callingUid);
2595 }
2596 } finally {
2597 accounts.accountsDb.endTransaction();
2598 if (isChanged) {
2599 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2600 sendNotificationAccountUpdated(account, accounts);
2601 sendAccountsChangedBroadcast(accounts.userId);
2602 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002603 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002604 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002605 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002606 }
2607
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002608 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002609 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002610 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002611 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2612 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002613 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002614 + ", pid " + Binder.getCallingPid());
2615 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002616 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002617 int userId = UserHandle.getCallingUserId();
2618 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002619 String msg = String.format(
2620 "uid %s cannot clear passwords for accounts of type: %s",
2621 callingUid,
2622 account.type);
2623 throw new SecurityException(msg);
2624 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002625 long identityToken = clearCallingIdentity();
2626 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002627 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002628 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002629 } finally {
2630 restoreCallingIdentity(identityToken);
2631 }
Fred Quintana60307342009-03-24 22:48:12 -07002632 }
2633
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002634 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002635 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002636 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002637 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2638 Log.v(TAG, "setUserData: " + account
2639 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002640 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002641 + ", pid " + Binder.getCallingPid());
2642 }
Fred Quintana382601f2010-03-25 12:25:10 -07002643 if (key == null) throw new IllegalArgumentException("key is null");
2644 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002645 int userId = UserHandle.getCallingUserId();
2646 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002647 String msg = String.format(
2648 "uid %s cannot set user data for accounts of type: %s",
2649 callingUid,
2650 account.type);
2651 throw new SecurityException(msg);
2652 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002653 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002654 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002655 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002656 if (!accountExistsCache(accounts, account)) {
2657 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002658 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002659 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002660 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002661 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002662 }
2663 }
2664
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002665 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2666 synchronized (accounts.cacheLock) {
2667 if (accounts.accountCache.containsKey(account.type)) {
2668 for (Account acc : accounts.accountCache.get(account.type)) {
2669 if (acc.name.equals(account.name)) {
2670 return true;
2671 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002672 }
2673 }
2674 }
2675 return false;
2676 }
2677
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002678 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002679 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002680 synchronized (accounts.dbLock) {
2681 accounts.accountsDb.beginTransaction();
2682 try {
2683 long accountId = accounts.accountsDb.findDeAccountId(account);
2684 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002685 return;
2686 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002687 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2688 if (extrasId < 0) {
2689 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2690 if (extrasId < 0) {
2691 return;
2692 }
2693 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2694 return;
2695 }
2696 accounts.accountsDb.setTransactionSuccessful();
2697 } finally {
2698 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002699 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002700 synchronized (accounts.cacheLock) {
2701 writeUserDataIntoCacheLocked(accounts, account, key, value);
2702 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002703 }
2704 }
2705
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002706 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002707 if (result == null) {
2708 Log.e(TAG, "the result is unexpectedly null", new Exception());
2709 }
2710 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2711 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2712 + response);
2713 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002714 try {
2715 response.onResult(result);
2716 } catch (RemoteException e) {
2717 // if the caller is dead then there is no one to care about remote
2718 // exceptions
2719 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2720 Log.v(TAG, "failure while notifying response", e);
2721 }
2722 }
2723 }
2724
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002725 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002726 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2727 final String authTokenType)
2728 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002729 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2730 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002731
Fred Quintanad9640ec2012-05-23 12:37:00 -07002732 final int callingUid = getCallingUid();
2733 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002734 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002735 throw new SecurityException("can only call from system");
2736 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002737 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002738 long identityToken = clearCallingIdentity();
2739 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002740 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002741 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2742 false /* stripAuthTokenFromResult */, null /* accountName */,
2743 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002744 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002745 protected String toDebugString(long now) {
2746 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002747 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002748 + ", authTokenType " + authTokenType;
2749 }
2750
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002751 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002752 public void run() throws RemoteException {
2753 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2754 }
2755
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002756 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002757 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002758 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002759 if (result != null) {
2760 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2761 Bundle bundle = new Bundle();
2762 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2763 super.onResult(bundle);
2764 return;
2765 } else {
2766 super.onResult(result);
2767 }
2768 }
2769 }.bind();
2770 } finally {
2771 restoreCallingIdentity(identityToken);
2772 }
2773 }
2774
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002775 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002776 public void getAuthToken(
2777 IAccountManagerResponse response,
2778 final Account account,
2779 final String authTokenType,
2780 final boolean notifyOnAuthFailure,
2781 final boolean expectActivityLaunch,
2782 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002783 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002784 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2785 Log.v(TAG, "getAuthToken: " + account
2786 + ", response " + response
2787 + ", authTokenType " + authTokenType
2788 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2789 + ", expectActivityLaunch " + expectActivityLaunch
2790 + ", caller's uid " + Binder.getCallingUid()
2791 + ", pid " + Binder.getCallingPid());
2792 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002793 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002794 try {
2795 if (account == null) {
2796 Slog.w(TAG, "getAuthToken called with null account");
2797 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2798 return;
2799 }
2800 if (authTokenType == null) {
2801 Slog.w(TAG, "getAuthToken called with null authTokenType");
2802 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2803 return;
2804 }
2805 } catch (RemoteException e) {
2806 Slog.w(TAG, "Failed to report error back to the client." + e);
2807 return;
2808 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002809 int userId = UserHandle.getCallingUserId();
2810 long ident = Binder.clearCallingIdentity();
2811 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002812 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002813 try {
2814 accounts = getUserAccounts(userId);
2815 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2816 AuthenticatorDescription.newKey(account.type), accounts.userId);
2817 } finally {
2818 Binder.restoreCallingIdentity(ident);
2819 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002820
Costin Manolachea40c6302010-12-13 14:50:45 -08002821 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002822 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002823
2824 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002825 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002826 final boolean permissionGranted =
2827 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002828
Carlos Valdivia91979be2015-05-22 14:11:35 -07002829 // Get the calling package. We will use it for the purpose of caching.
2830 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002831 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002832 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002833 try {
2834 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2835 } finally {
2836 Binder.restoreCallingIdentity(ident);
2837 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002838 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2839 String msg = String.format(
2840 "Uid %s is attempting to illegally masquerade as package %s!",
2841 callerUid,
2842 callerPkg);
2843 throw new SecurityException(msg);
2844 }
2845
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002846 // let authenticator know the identity of the caller
2847 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2848 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002849
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002850 if (notifyOnAuthFailure) {
2851 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002852 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002853
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002854 long identityToken = clearCallingIdentity();
2855 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002856 // Distill the caller's package signatures into a single digest.
2857 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2858
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002859 // if the caller has permission, do the peek. otherwise go the more expensive
2860 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002861 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002862 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002863 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002864 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002865 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2866 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2867 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002868 onResult(response, result);
2869 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002870 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002871 }
2872
Carlos Valdivia91979be2015-05-22 14:11:35 -07002873 if (customTokens) {
2874 /*
2875 * Look up tokens in the new cache only if the loginOptions don't have parameters
2876 * outside of those expected to be injected by the AccountManager, e.g.
2877 * ANDORID_PACKAGE_NAME.
2878 */
2879 String token = readCachedTokenInternal(
2880 accounts,
2881 account,
2882 authTokenType,
2883 callerPkg,
2884 callerPkgSigDigest);
2885 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002886 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2887 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2888 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002889 Bundle result = new Bundle();
2890 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2891 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2892 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2893 onResult(response, result);
2894 return;
2895 }
2896 }
2897
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002898 new Session(
2899 accounts,
2900 response,
2901 account.type,
2902 expectActivityLaunch,
2903 false /* stripAuthTokenFromResult */,
2904 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002905 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002906 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002907 protected String toDebugString(long now) {
2908 if (loginOptions != null) loginOptions.keySet();
2909 return super.toDebugString(now) + ", getAuthToken"
2910 + ", " + account
2911 + ", authTokenType " + authTokenType
2912 + ", loginOptions " + loginOptions
2913 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2914 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002915
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002916 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002917 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002918 // If the caller doesn't have permission then create and return the
2919 // "grant permission" intent instead of the "getAuthToken" intent.
2920 if (!permissionGranted) {
2921 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2922 } else {
2923 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2924 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002925 }
2926
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002927 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002928 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002929 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002930 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002931 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002932 Intent intent = newGrantCredentialsPermissionIntent(
2933 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002934 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002935 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002936 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002937 authTokenType,
2938 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002939 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002940 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002941 onResult(bundle);
2942 return;
2943 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002944 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002945 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002946 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2947 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002948 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002949 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002950 "the type and name should not be empty");
2951 return;
2952 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002953 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002954 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002955 saveAuthTokenToDatabase(
2956 mAccounts,
2957 resultAccount,
2958 authTokenType,
2959 authToken);
2960 }
2961 long expiryMillis = result.getLong(
2962 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2963 if (customTokens
2964 && expiryMillis > System.currentTimeMillis()) {
2965 saveCachedToken(
2966 mAccounts,
2967 account,
2968 callerPkg,
2969 callerPkgSigDigest,
2970 authTokenType,
2971 authToken,
2972 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002973 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002974 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002975
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002976 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002977 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002978 /*
2979 * Make sure that the supplied intent is owned by the authenticator
2980 * giving it to the system. Otherwise a malicious authenticator could
2981 * have users launching arbitrary activities by tricking users to
2982 * interact with malicious notifications.
2983 */
tiansiminga8868bf2017-09-20 13:59:13 +08002984 if (!checkKeyIntent(
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002985 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08002986 intent)) {
2987 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2988 "invalid intent in bundle returned");
2989 return;
2990 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002991 doNotification(
2992 mAccounts,
2993 account,
2994 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002995 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002996 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002997 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002998 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002999 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003000 }.bind();
3001 } finally {
3002 restoreCallingIdentity(identityToken);
3003 }
Fred Quintana60307342009-03-24 22:48:12 -07003004 }
3005
Carlos Valdivia91979be2015-05-22 14:11:35 -07003006 private byte[] calculatePackageSignatureDigest(String callerPkg) {
3007 MessageDigest digester;
3008 try {
3009 digester = MessageDigest.getInstance("SHA-256");
3010 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
3011 callerPkg, PackageManager.GET_SIGNATURES);
3012 for (Signature sig : pkgInfo.signatures) {
3013 digester.update(sig.toByteArray());
3014 }
3015 } catch (NoSuchAlgorithmException x) {
3016 Log.wtf(TAG, "SHA-256 should be available", x);
3017 digester = null;
3018 } catch (NameNotFoundException e) {
3019 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
3020 digester = null;
3021 }
3022 return (digester == null) ? null : digester.digest();
3023 }
3024
Dianne Hackborn41203752012-08-31 14:05:51 -07003025 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003026 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003027 int uid = intent.getIntExtra(
3028 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
3029 String authTokenType = intent.getStringExtra(
3030 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07003031 final String titleAndSubtitle =
3032 mContext.getString(R.string.permission_request_notification_with_subtitle,
3033 account.name);
3034 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07003035 String title = titleAndSubtitle;
3036 String subtitle = "";
3037 if (index > 0) {
3038 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04003039 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07003040 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07003041 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003042 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003043 Notification n =
3044 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3045 .setSmallIcon(android.R.drawable.stat_sys_warning)
3046 .setWhen(0)
3047 .setColor(contextForUser.getColor(
3048 com.android.internal.R.color.system_notification_accent_color))
3049 .setContentTitle(title)
3050 .setContentText(subtitle)
3051 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3052 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3053 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003054 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003055 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003056 }
3057
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003058 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3059 int uid, AccountAuthenticatorResponse response, String authTokenType,
3060 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003061
3062 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003063
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003064 if (startInNewTask) {
3065 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3066 // Since it was set in Eclair+ we can't change it without breaking apps using
3067 // the intent from a non-Activity context. This is the default behavior.
3068 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3069 }
Chris Wren717a8812017-03-31 15:34:39 -04003070 intent.addCategory(getCredentialPermissionNotificationId(account,
3071 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003072 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003073 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3074 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003075 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003076
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003077 return intent;
3078 }
3079
Chris Wren717a8812017-03-31 15:34:39 -04003080 private NotificationId getCredentialPermissionNotificationId(Account account,
3081 String authTokenType, int uid) {
3082 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003083 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003084 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003085 final Pair<Pair<Account, String>, Integer> key =
3086 new Pair<Pair<Account, String>, Integer>(
3087 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003088 nId = accounts.credentialsPermissionNotificationIds.get(key);
3089 if (nId == null) {
3090 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3091 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3092 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3093 nId = new NotificationId(tag, id);
3094 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003095 }
3096 }
Chris Wren717a8812017-03-31 15:34:39 -04003097 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003098 }
3099
Chris Wren717a8812017-03-31 15:34:39 -04003100 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3101 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003102 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003103 nId = accounts.signinRequiredNotificationIds.get(account);
3104 if (nId == null) {
3105 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3106 + ":" + account.hashCode();
3107 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3108 nId = new NotificationId(tag, id);
3109 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003110 }
3111 }
Chris Wren717a8812017-03-31 15:34:39 -04003112 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003113 }
3114
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003115 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003116 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003117 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003118 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003119 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3121 Log.v(TAG, "addAccount: accountType " + accountType
3122 + ", response " + response
3123 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003124 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003125 + ", expectActivityLaunch " + expectActivityLaunch
3126 + ", caller's uid " + Binder.getCallingUid()
3127 + ", pid " + Binder.getCallingPid());
3128 }
Fred Quintana382601f2010-03-25 12:25:10 -07003129 if (response == null) throw new IllegalArgumentException("response is null");
3130 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003131
Amith Yamasani71e6c692013-03-24 17:39:28 -07003132 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003133 final int uid = Binder.getCallingUid();
3134 final int userId = UserHandle.getUserId(uid);
3135 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003136 try {
3137 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3138 "User is not allowed to add an account!");
3139 } catch (RemoteException re) {
3140 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003141 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003142 return;
3143 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003144 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003145 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003146 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3147 "User cannot modify accounts of this type (policy).");
3148 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003149 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003150 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3151 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003152 return;
3153 }
3154
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003155 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003156 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3157 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3158 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3159
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003160 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003161 long identityToken = clearCallingIdentity();
3162 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003163 UserAccounts accounts = getUserAccounts(usrId);
3164 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003165 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3166 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003167 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003168 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003169 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003170 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003171 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003172 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003173 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003174 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003175
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003176 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003177 protected String toDebugString(long now) {
3178 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003179 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003180 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003181 }
3182 }.bind();
3183 } finally {
3184 restoreCallingIdentity(identityToken);
3185 }
Fred Quintana60307342009-03-24 22:48:12 -07003186 }
3187
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003188 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003189 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3190 final String authTokenType, final String[] requiredFeatures,
3191 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003192 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003193 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3195 Log.v(TAG, "addAccount: accountType " + accountType
3196 + ", response " + response
3197 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003198 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003199 + ", expectActivityLaunch " + expectActivityLaunch
3200 + ", caller's uid " + Binder.getCallingUid()
3201 + ", pid " + Binder.getCallingPid()
3202 + ", for user id " + userId);
3203 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003204 Preconditions.checkArgument(response != null, "response cannot be null");
3205 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003206 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003207 if (isCrossUser(callingUid, userId)) {
3208 throw new SecurityException(
3209 String.format(
3210 "User %s trying to add account for %s" ,
3211 UserHandle.getCallingUserId(),
3212 userId));
3213 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003214
3215 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003216 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003217 try {
3218 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3219 "User is not allowed to add an account!");
3220 } catch (RemoteException re) {
3221 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003222 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003223 return;
3224 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003225 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003226 try {
3227 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3228 "User cannot modify accounts of this type (policy).");
3229 } catch (RemoteException re) {
3230 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003231 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3232 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003233 return;
3234 }
3235
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003236 final int pid = Binder.getCallingPid();
3237 final int uid = Binder.getCallingUid();
3238 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3239 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3240 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3241
3242 long identityToken = clearCallingIdentity();
3243 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003244 UserAccounts accounts = getUserAccounts(userId);
3245 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003246 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3247 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003248 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003249 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003250 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003251 @Override
3252 public void run() throws RemoteException {
3253 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3254 options);
3255 }
3256
3257 @Override
3258 protected String toDebugString(long now) {
3259 return super.toDebugString(now) + ", addAccount"
3260 + ", accountType " + accountType
3261 + ", requiredFeatures "
3262 + (requiredFeatures != null
3263 ? TextUtils.join(",", requiredFeatures)
3264 : null);
3265 }
3266 }.bind();
3267 } finally {
3268 restoreCallingIdentity(identityToken);
3269 }
3270 }
3271
Sandra Kwan78812282015-11-04 11:19:47 -08003272 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003273 public void startAddAccountSession(
3274 final IAccountManagerResponse response,
3275 final String accountType,
3276 final String authTokenType,
3277 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003278 final boolean expectActivityLaunch,
3279 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003280 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3282 Log.v(TAG,
3283 "startAddAccountSession: accountType " + accountType
3284 + ", response " + response
3285 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003286 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003287 + ", expectActivityLaunch " + expectActivityLaunch
3288 + ", caller's uid " + Binder.getCallingUid()
3289 + ", pid " + Binder.getCallingPid());
3290 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003291 Preconditions.checkArgument(response != null, "response cannot be null");
3292 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003293
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003294 final int uid = Binder.getCallingUid();
3295 final int userId = UserHandle.getUserId(uid);
3296 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003297 try {
3298 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3299 "User is not allowed to add an account!");
3300 } catch (RemoteException re) {
3301 }
3302 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3303 return;
3304 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003305 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003306 try {
3307 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3308 "User cannot modify accounts of this type (policy).");
3309 } catch (RemoteException re) {
3310 }
3311 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3312 userId);
3313 return;
3314 }
Sandra Kwan78812282015-11-04 11:19:47 -08003315 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003316 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3317 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3318 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3319
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003320 // Check to see if the Password should be included to the caller.
3321 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3322 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003323 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003324
Sandra Kwan78812282015-11-04 11:19:47 -08003325 long identityToken = clearCallingIdentity();
3326 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003327 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003328 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3329 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003330 new StartAccountSession(
3331 accounts,
3332 response,
3333 accountType,
3334 expectActivityLaunch,
3335 null /* accountName */,
3336 false /* authDetailsRequired */,
3337 true /* updateLastAuthenticationTime */,
3338 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003339 @Override
3340 public void run() throws RemoteException {
3341 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3342 requiredFeatures, options);
3343 }
3344
3345 @Override
3346 protected String toDebugString(long now) {
3347 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3348 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3349 + accountType + ", requiredFeatures "
3350 + (requiredFeatures != null ? requiredFeaturesStr : null);
3351 }
3352 }.bind();
3353 } finally {
3354 restoreCallingIdentity(identityToken);
3355 }
3356 }
3357
3358 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3359 private abstract class StartAccountSession extends Session {
3360
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003361 private final boolean mIsPasswordForwardingAllowed;
3362
3363 public StartAccountSession(
3364 UserAccounts accounts,
3365 IAccountManagerResponse response,
3366 String accountType,
3367 boolean expectActivityLaunch,
3368 String accountName,
3369 boolean authDetailsRequired,
3370 boolean updateLastAuthenticationTime,
3371 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003372 super(accounts, response, accountType, expectActivityLaunch,
3373 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3374 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003375 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003376 }
3377
3378 @Override
3379 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003380 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003381 mNumResults++;
3382 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003383 if (result != null
3384 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
tiansiminga8868bf2017-09-20 13:59:13 +08003385 if (!checkKeyIntent(
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003386 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08003387 intent)) {
3388 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
3389 "invalid intent in bundle returned");
3390 return;
3391 }
Sandra Kwan78812282015-11-04 11:19:47 -08003392 }
Sandra Kwan78812282015-11-04 11:19:47 -08003393 IAccountManagerResponse response;
3394 if (mExpectActivityLaunch && result != null
3395 && result.containsKey(AccountManager.KEY_INTENT)) {
3396 response = mResponse;
3397 } else {
3398 response = getResponseAndClose();
3399 }
3400 if (response == null) {
3401 return;
3402 }
3403 if (result == null) {
3404 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3405 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3406 + response);
3407 }
3408 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3409 "null bundle returned");
3410 return;
3411 }
3412
3413 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3414 // All AccountManager error codes are greater
3415 // than 0
3416 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3417 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3418 return;
3419 }
3420
Hongming Jin368aa192016-07-29 14:29:54 -07003421 // Omit passwords if the caller isn't permitted to see them.
3422 if (!mIsPasswordForwardingAllowed) {
3423 result.remove(AccountManager.KEY_PASSWORD);
3424 }
3425
Sandra Kwan78812282015-11-04 11:19:47 -08003426 // Strip auth token from result.
3427 result.remove(AccountManager.KEY_AUTHTOKEN);
3428
3429 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3430 Log.v(TAG,
3431 getClass().getSimpleName() + " calling onResult() on response " + response);
3432 }
3433
3434 // Get the session bundle created by authenticator. The
3435 // bundle contains data necessary for finishing the session
3436 // later. The session bundle will be encrypted here and
3437 // decrypted later when trying to finish the session.
3438 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3439 if (sessionBundle != null) {
3440 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3441 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003442 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003443 Log.w(TAG, "Account type in session bundle doesn't match request.");
3444 }
3445 // Add accountType info to session bundle. This will
3446 // override any value set by authenticator.
3447 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3448
3449 // Encrypt session bundle before returning to caller.
3450 try {
3451 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3452 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3453 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3454 } catch (GeneralSecurityException e) {
3455 if (Log.isLoggable(TAG, Log.DEBUG)) {
3456 Log.v(TAG, "Failed to encrypt session bundle!", e);
3457 }
3458 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3459 "failed to encrypt session bundle");
3460 return;
3461 }
3462 }
3463
3464 sendResponse(response, result);
3465 }
3466 }
3467
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003468 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003469 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003470 @NonNull Bundle sessionBundle,
3471 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003472 Bundle appInfo,
3473 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003474 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003475 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003476 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3477 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003478 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003479 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003480 + ", caller's uid " + callingUid
3481 + ", caller's user id " + UserHandle.getCallingUserId()
3482 + ", pid " + Binder.getCallingPid()
3483 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003484 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003485 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003486 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3487 // Account type is added to it before encryption.
3488 if (sessionBundle == null || sessionBundle.size() == 0) {
3489 throw new IllegalArgumentException("sessionBundle is empty");
3490 }
3491
Dmitry Dementyev52745472016-12-02 10:27:45 -08003492 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003493 if (isCrossUser(callingUid, userId)) {
3494 throw new SecurityException(
3495 String.format(
3496 "User %s trying to finish session for %s without cross user permission",
3497 UserHandle.getCallingUserId(),
3498 userId));
3499 }
3500
Sandra Kwan0b84b452016-01-20 15:25:42 -08003501 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003502 sendErrorResponse(response,
3503 AccountManager.ERROR_CODE_USER_RESTRICTED,
3504 "User is not allowed to add an account!");
3505 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3506 return;
3507 }
3508
3509 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003510 final Bundle decryptedBundle;
3511 final String accountType;
3512 // First decrypt session bundle to get account type for checking permission.
3513 try {
3514 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3515 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3516 if (decryptedBundle == null) {
3517 sendErrorResponse(
3518 response,
3519 AccountManager.ERROR_CODE_BAD_REQUEST,
3520 "failed to decrypt session bundle");
3521 return;
3522 }
3523 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3524 // Account type cannot be null. This should not happen if session bundle was created
3525 // properly by #StartAccountSession.
3526 if (TextUtils.isEmpty(accountType)) {
3527 sendErrorResponse(
3528 response,
3529 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3530 "accountType is empty");
3531 return;
3532 }
3533
3534 // If by any chances, decryptedBundle contains colliding keys with
3535 // system info
3536 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3537 // update credentials flow, we should replace with the new values of the current call.
3538 if (appInfo != null) {
3539 decryptedBundle.putAll(appInfo);
3540 }
3541
3542 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003543 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003544 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3545 } catch (GeneralSecurityException e) {
3546 if (Log.isLoggable(TAG, Log.DEBUG)) {
3547 Log.v(TAG, "Failed to decrypt session bundle!", e);
3548 }
3549 sendErrorResponse(
3550 response,
3551 AccountManager.ERROR_CODE_BAD_REQUEST,
3552 "failed to decrypt session bundle");
3553 return;
3554 }
3555
Sandra Kwan0b84b452016-01-20 15:25:42 -08003556 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003557 sendErrorResponse(
3558 response,
3559 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3560 "User cannot modify accounts of this type (policy).");
3561 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3562 userId);
3563 return;
3564 }
3565
3566 long identityToken = clearCallingIdentity();
3567 try {
3568 UserAccounts accounts = getUserAccounts(userId);
3569 logRecordWithUid(
3570 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003571 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3572 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003573 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003574 new Session(
3575 accounts,
3576 response,
3577 accountType,
3578 expectActivityLaunch,
3579 true /* stripAuthTokenFromResult */,
3580 null /* accountName */,
3581 false /* authDetailsRequired */,
3582 true /* updateLastAuthenticationTime */) {
3583 @Override
3584 public void run() throws RemoteException {
3585 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3586 }
3587
3588 @Override
3589 protected String toDebugString(long now) {
3590 return super.toDebugString(now)
3591 + ", finishSession"
3592 + ", accountType " + accountType;
3593 }
3594 }.bind();
3595 } finally {
3596 restoreCallingIdentity(identityToken);
3597 }
3598 }
3599
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003600 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003601 final DevicePolicyManagerInternal dpmi =
3602 LocalServices.getService(DevicePolicyManagerInternal.class);
3603 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003604 if (dpmi == null) {
3605 intent = getDefaultCantAddAccountIntent(errorCode);
3606 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003607 intent = dpmi.createUserRestrictionSupportIntent(userId,
3608 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3609 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3610 intent = dpmi.createShowAdminSupportIntent(userId, false);
3611 }
3612 if (intent == null) {
3613 intent = getDefaultCantAddAccountIntent(errorCode);
3614 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003615 long identityToken = clearCallingIdentity();
3616 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003617 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003618 } finally {
3619 restoreCallingIdentity(identityToken);
3620 }
3621 }
3622
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003623 /**
3624 * Called when we don't know precisely who is preventing us from adding an account.
3625 */
3626 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3627 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3628 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3629 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3630 return cantAddAccount;
3631 }
3632
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003633 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003634 public void confirmCredentialsAsUser(
3635 IAccountManagerResponse response,
3636 final Account account,
3637 final Bundle options,
3638 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003639 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003640 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003641 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3643 Log.v(TAG, "confirmCredentials: " + account
3644 + ", response " + response
3645 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003646 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003647 + ", pid " + Binder.getCallingPid());
3648 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003649 // Only allow the system process to read accounts of other users
3650 if (isCrossUser(callingUid, userId)) {
3651 throw new SecurityException(
3652 String.format(
3653 "User %s trying to confirm account credentials for %s" ,
3654 UserHandle.getCallingUserId(),
3655 userId));
3656 }
Fred Quintana382601f2010-03-25 12:25:10 -07003657 if (response == null) throw new IllegalArgumentException("response is null");
3658 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003659 long identityToken = clearCallingIdentity();
3660 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003661 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003662 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003663 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003664 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003665 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003666 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003667 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003668 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003669 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003670 protected String toDebugString(long now) {
3671 return super.toDebugString(now) + ", confirmCredentials"
3672 + ", " + account;
3673 }
3674 }.bind();
3675 } finally {
3676 restoreCallingIdentity(identityToken);
3677 }
Fred Quintana60307342009-03-24 22:48:12 -07003678 }
3679
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003680 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003681 public void updateCredentials(IAccountManagerResponse response, final Account account,
3682 final String authTokenType, final boolean expectActivityLaunch,
3683 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003684 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3686 Log.v(TAG, "updateCredentials: " + account
3687 + ", response " + response
3688 + ", authTokenType " + authTokenType
3689 + ", expectActivityLaunch " + expectActivityLaunch
3690 + ", caller's uid " + Binder.getCallingUid()
3691 + ", pid " + Binder.getCallingPid());
3692 }
Fred Quintana382601f2010-03-25 12:25:10 -07003693 if (response == null) throw new IllegalArgumentException("response is null");
3694 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003695 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003696 long identityToken = clearCallingIdentity();
3697 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003698 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003699 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003700 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003701 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003702 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003703 public void run() throws RemoteException {
3704 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3705 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003706 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003707 protected String toDebugString(long now) {
3708 if (loginOptions != null) loginOptions.keySet();
3709 return super.toDebugString(now) + ", updateCredentials"
3710 + ", " + account
3711 + ", authTokenType " + authTokenType
3712 + ", loginOptions " + loginOptions;
3713 }
3714 }.bind();
3715 } finally {
3716 restoreCallingIdentity(identityToken);
3717 }
Fred Quintana60307342009-03-24 22:48:12 -07003718 }
3719
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003720 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003721 public void startUpdateCredentialsSession(
3722 IAccountManagerResponse response,
3723 final Account account,
3724 final String authTokenType,
3725 final boolean expectActivityLaunch,
3726 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003727 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003728 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3729 Log.v(TAG,
3730 "startUpdateCredentialsSession: " + account + ", response " + response
3731 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3732 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3733 + ", pid " + Binder.getCallingPid());
3734 }
3735 if (response == null) {
3736 throw new IllegalArgumentException("response is null");
3737 }
3738 if (account == null) {
3739 throw new IllegalArgumentException("account is null");
3740 }
Sandra Kwana578d112015-12-16 16:01:43 -08003741
3742 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003743 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003744
3745 // Check to see if the Password should be included to the caller.
3746 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3747 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003748 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003749
Sandra Kwane68c37e2015-11-12 17:11:49 -08003750 long identityToken = clearCallingIdentity();
3751 try {
3752 UserAccounts accounts = getUserAccounts(userId);
3753 new StartAccountSession(
3754 accounts,
3755 response,
3756 account.type,
3757 expectActivityLaunch,
3758 account.name,
3759 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003760 true /* updateLastCredentialTime */,
3761 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003762 @Override
3763 public void run() throws RemoteException {
3764 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3765 loginOptions);
3766 }
3767
3768 @Override
3769 protected String toDebugString(long now) {
3770 if (loginOptions != null)
3771 loginOptions.keySet();
3772 return super.toDebugString(now)
3773 + ", startUpdateCredentialsSession"
3774 + ", " + account
3775 + ", authTokenType " + authTokenType
3776 + ", loginOptions " + loginOptions;
3777 }
3778 }.bind();
3779 } finally {
3780 restoreCallingIdentity(identityToken);
3781 }
3782 }
3783
3784 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003785 public void isCredentialsUpdateSuggested(
3786 IAccountManagerResponse response,
3787 final Account account,
3788 final String statusToken) {
3789 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3790 Log.v(TAG,
3791 "isCredentialsUpdateSuggested: " + account + ", response " + response
3792 + ", caller's uid " + Binder.getCallingUid()
3793 + ", pid " + Binder.getCallingPid());
3794 }
3795 if (response == null) {
3796 throw new IllegalArgumentException("response is null");
3797 }
3798 if (account == null) {
3799 throw new IllegalArgumentException("account is null");
3800 }
3801 if (TextUtils.isEmpty(statusToken)) {
3802 throw new IllegalArgumentException("status token is empty");
3803 }
3804
Sandra Kwan390c9d22016-01-12 14:13:37 -08003805 int usrId = UserHandle.getCallingUserId();
3806 long identityToken = clearCallingIdentity();
3807 try {
3808 UserAccounts accounts = getUserAccounts(usrId);
3809 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3810 false /* stripAuthTokenFromResult */, account.name,
3811 false /* authDetailsRequired */) {
3812 @Override
3813 protected String toDebugString(long now) {
3814 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3815 + ", " + account;
3816 }
3817
3818 @Override
3819 public void run() throws RemoteException {
3820 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3821 }
3822
3823 @Override
3824 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003825 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003826 IAccountManagerResponse response = getResponseAndClose();
3827 if (response == null) {
3828 return;
3829 }
3830
3831 if (result == null) {
3832 sendErrorResponse(
3833 response,
3834 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3835 "null bundle");
3836 return;
3837 }
3838
3839 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3840 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3841 + response);
3842 }
3843 // Check to see if an error occurred. We know if an error occurred because all
3844 // error codes are greater than 0.
3845 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3846 sendErrorResponse(response,
3847 result.getInt(AccountManager.KEY_ERROR_CODE),
3848 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3849 return;
3850 }
3851 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3852 sendErrorResponse(
3853 response,
3854 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3855 "no result in response");
3856 return;
3857 }
3858 final Bundle newResult = new Bundle();
3859 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3860 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3861 sendResponse(response, newResult);
3862 }
3863 }.bind();
3864 } finally {
3865 restoreCallingIdentity(identityToken);
3866 }
3867 }
3868
3869 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003870 public void editProperties(IAccountManagerResponse response, final String accountType,
3871 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003872 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003873 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3874 Log.v(TAG, "editProperties: accountType " + accountType
3875 + ", response " + response
3876 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003877 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003878 + ", pid " + Binder.getCallingPid());
3879 }
Fred Quintana382601f2010-03-25 12:25:10 -07003880 if (response == null) throw new IllegalArgumentException("response is null");
3881 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003882 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003883 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3884 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003885 String msg = String.format(
3886 "uid %s cannot edit authenticator properites for account type: %s",
3887 callingUid,
3888 accountType);
3889 throw new SecurityException(msg);
3890 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003891 long identityToken = clearCallingIdentity();
3892 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003893 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003894 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003895 true /* stripAuthTokenFromResult */, null /* accountName */,
3896 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003897 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003898 public void run() throws RemoteException {
3899 mAuthenticator.editProperties(this, mAccountType);
3900 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003901 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003902 protected String toDebugString(long now) {
3903 return super.toDebugString(now) + ", editProperties"
3904 + ", accountType " + accountType;
3905 }
3906 }.bind();
3907 } finally {
3908 restoreCallingIdentity(identityToken);
3909 }
Fred Quintana60307342009-03-24 22:48:12 -07003910 }
3911
Amith Yamasani12747872015-12-07 14:19:49 -08003912 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003913 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3914 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003915 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003916 throw new SecurityException("Can be called only by system UID");
3917 }
3918 Preconditions.checkNotNull(account, "account cannot be null");
3919 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3920 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3921
3922 final int userId = userHandle.getIdentifier();
3923
3924 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3925
3926 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003927 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003928 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003929 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003930 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003931 return false;
3932 }
3933 }
3934
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003935 // Returns package with oldest target SDK for given UID.
3936 private String getPackageNameForUid(int uid) {
3937 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3938 if (ArrayUtils.isEmpty(packageNames)) {
3939 return null;
3940 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003941 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003942 if (packageNames.length == 1) {
3943 return packageName;
3944 }
3945 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003946 int oldestVersion = Integer.MAX_VALUE;
3947 for (String name : packageNames) {
3948 try {
3949 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3950 if (applicationInfo != null) {
3951 int version = applicationInfo.targetSdkVersion;
3952 if (version < oldestVersion) {
3953 oldestVersion = version;
3954 packageName = name;
3955 }
3956 }
3957 } catch (NameNotFoundException e) {
3958 // skip
3959 }
3960 }
3961 return packageName;
3962 }
3963
Svet Ganovf6d424f12016-09-20 20:18:53 -07003964 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3965 int uid) {
3966 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003967 packageName = getPackageNameForUid(uid);
3968 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003969 return false;
3970 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003971 }
3972
3973 // Use null token which means any token. Having a token means the package
3974 // is trusted by the authenticator, hence it is fine to access the account.
3975 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3976 return true;
3977 }
3978 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003979 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003980
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003981 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003982 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003983 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003984 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003985 }
3986
3987 @Override
3988 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3989 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003990 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003991 throw new SecurityException("Can be called only by system UID");
3992 }
3993
3994 Preconditions.checkNotNull(account, "account cannot be null");
3995 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3996 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3997
3998 final int userId = userHandle.getIdentifier();
3999
4000 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
4001
4002 final int uid;
4003 try {
4004 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
4005 } catch (NameNotFoundException e) {
4006 Slog.e(TAG, "Unknown package " + packageName);
4007 return null;
4008 }
4009
4010 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
4011
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07004012 final long identity = Binder.clearCallingIdentity();
4013 try {
4014 return PendingIntent.getActivityAsUser(
4015 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
4016 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
4017 null, new UserHandle(userId)).getIntentSender();
4018 } finally {
4019 Binder.restoreCallingIdentity(identity);
4020 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004021 }
4022
4023 private Intent newRequestAccountAccessIntent(Account account, String packageName,
4024 int uid, RemoteCallback callback) {
4025 return newGrantCredentialsPermissionIntent(account, packageName, uid,
4026 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
4027 @Override
4028 public void onResult(Bundle value) throws RemoteException {
4029 handleAuthenticatorResponse(true);
4030 }
4031
4032 @Override
4033 public void onRequestContinued() {
4034 /* ignore */
4035 }
4036
4037 @Override
4038 public void onError(int errorCode, String errorMessage) throws RemoteException {
4039 handleAuthenticatorResponse(false);
4040 }
4041
4042 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
4043 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07004044 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004045 UserHandle.getUserHandleForUid(uid));
4046 if (callback != null) {
4047 Bundle result = new Bundle();
4048 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4049 callback.sendResult(result);
4050 }
4051 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004052 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004053 }
4054
4055 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004056 public boolean someUserHasAccount(@NonNull final Account account) {
4057 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4058 throw new SecurityException("Only system can check for accounts across users");
4059 }
4060 final long token = Binder.clearCallingIdentity();
4061 try {
4062 AccountAndUser[] allAccounts = getAllAccounts();
4063 for (int i = allAccounts.length - 1; i >= 0; i--) {
4064 if (allAccounts[i].account.equals(account)) {
4065 return true;
4066 }
4067 }
4068 return false;
4069 } finally {
4070 Binder.restoreCallingIdentity(token);
4071 }
4072 }
4073
Fred Quintana33269202009-04-20 16:05:10 -07004074 private class GetAccountsByTypeAndFeatureSession extends Session {
4075 private final String[] mFeatures;
4076 private volatile Account[] mAccountsOfType = null;
4077 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4078 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004079 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004080 private final String mPackageName;
sunjianf29d5492017-05-11 15:42:31 -07004081 private final boolean mIncludeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004082
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004083 public GetAccountsByTypeAndFeatureSession(
4084 UserAccounts accounts,
4085 IAccountManagerResponse response,
4086 String type,
4087 String[] features,
4088 int callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004089 String packageName,
4090 boolean includeManagedNotVisible) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004091 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004092 true /* stripAuthTokenFromResult */, null /* accountName */,
4093 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004094 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004095 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004096 mPackageName = packageName;
sunjianf29d5492017-05-11 15:42:31 -07004097 mIncludeManagedNotVisible = includeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004098 }
4099
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004100 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004101 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004102 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
sunjianf29d5492017-05-11 15:42:31 -07004103 mCallingUid, mPackageName, mIncludeManagedNotVisible);
Fred Quintana33269202009-04-20 16:05:10 -07004104 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004105 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004106 mCurrentAccount = 0;
4107
4108 checkAccount();
4109 }
4110
4111 public void checkAccount() {
4112 if (mCurrentAccount >= mAccountsOfType.length) {
4113 sendResult();
4114 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004115 }
Fred Quintana33269202009-04-20 16:05:10 -07004116
Fred Quintana29e94b82010-03-10 12:11:51 -08004117 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4118 if (accountAuthenticator == null) {
4119 // It is possible that the authenticator has died, which is indicated by
4120 // mAuthenticator being set to null. If this happens then just abort.
4121 // There is no need to send back a result or error in this case since
4122 // that already happened when mAuthenticator was cleared.
4123 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4124 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4125 + " connected to the authenticator, " + toDebugString());
4126 }
4127 return;
4128 }
Fred Quintana33269202009-04-20 16:05:10 -07004129 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004130 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004131 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004132 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004133 }
4134 }
4135
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004136 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004137 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004138 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004139 mNumResults++;
4140 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004141 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004142 return;
4143 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004144 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004145 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4146 }
4147 mCurrentAccount++;
4148 checkAccount();
4149 }
4150
4151 public void sendResult() {
4152 IAccountManagerResponse response = getResponseAndClose();
4153 if (response != null) {
4154 try {
4155 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4156 for (int i = 0; i < accounts.length; i++) {
4157 accounts[i] = mAccountsWithFeatures.get(i);
4158 }
Fred Quintana56285a62010-12-02 14:20:51 -08004159 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4160 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4161 + response);
4162 }
Fred Quintana33269202009-04-20 16:05:10 -07004163 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004164 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004165 response.onResult(result);
4166 } catch (RemoteException e) {
4167 // if the caller is dead then there is no one to care about remote exceptions
4168 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4169 Log.v(TAG, "failure while notifying response", e);
4170 }
4171 }
4172 }
4173 }
4174
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004175 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004176 protected String toDebugString(long now) {
4177 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4178 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4179 }
4180 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004181
Amith Yamasani04e0d262012-02-14 11:50:53 -08004182 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004183 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004184 * @hide
4185 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004186 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004187 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004188 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004189 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004190 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4191 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004192 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004193 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004194 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004195 long identityToken = clearCallingIdentity();
4196 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004197 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004198 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004199 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004200 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004201 opPackageName,
4202 visibleAccountTypes,
4203 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004204 } finally {
4205 restoreCallingIdentity(identityToken);
4206 }
4207 }
4208
Amith Yamasanif29f2362012-04-05 18:29:52 -07004209 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004210 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004211 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004212 * @hide
4213 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004214 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004215 public AccountAndUser[] getRunningAccounts() {
4216 final int[] runningUserIds;
4217 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004218 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004219 } catch (RemoteException e) {
4220 // Running in system_server; should never happen
4221 throw new RuntimeException(e);
4222 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004223 return getAccounts(runningUserIds);
4224 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004225
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004226 /**
4227 * Returns accounts for all users, ignores visibility values.
4228 *
4229 * @hide
4230 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004231 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004232 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004233 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004234 final int[] userIds = new int[users.size()];
4235 for (int i = 0; i < userIds.length; i++) {
4236 userIds[i] = users.get(i).id;
4237 }
4238 return getAccounts(userIds);
4239 }
4240
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004241 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004242 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004243 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004244 for (int userId : userIds) {
4245 UserAccounts userAccounts = getUserAccounts(userId);
4246 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004247 Account[] accounts = getAccountsFromCache(
4248 userAccounts,
4249 null /* type */,
4250 Binder.getCallingUid(),
4251 null /* packageName */,
4252 false /* include managed not visible*/);
4253 for (Account account : accounts) {
4254 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004255 }
4256 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004257
4258 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4259 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004260 }
4261
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004262 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004263 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004264 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004265 int callingUid = Binder.getCallingUid();
4266 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004267 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004268 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004269 }
4270
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004271 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004272 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004273 String type,
4274 int userId,
4275 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004276 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004277 String opPackageName,
4278 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004279 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004280 // Only allow the system process to read accounts of other users
4281 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004282 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004283 && mContext.checkCallingOrSelfPermission(
4284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4285 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004286 throw new SecurityException("User " + UserHandle.getCallingUserId()
4287 + " trying to get account for " + userId);
4288 }
4289
Fred Quintana56285a62010-12-02 14:20:51 -08004290 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4291 Log.v(TAG, "getAccounts: accountType " + type
4292 + ", caller's uid " + Binder.getCallingUid()
4293 + ", pid " + Binder.getCallingPid());
4294 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004295
4296 // If the original calling app was using account choosing activity
4297 // provided by the framework or authenticator we'll passing in
4298 // the original caller's uid here, which is what should be used for filtering.
4299 List<String> managedTypes =
4300 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4301 if (packageUid != -1 &&
4302 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4303 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004304 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004305 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004306 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004307 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4308 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004309 if (visibleAccountTypes.isEmpty()
4310 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004311 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004312 } else if (visibleAccountTypes.contains(type)) {
4313 // Prune the list down to just the requested type.
4314 visibleAccountTypes = new ArrayList<>();
4315 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004316 } // else aggregate all the visible accounts (it won't matter if the
4317 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004318
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004319 long identityToken = clearCallingIdentity();
4320 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004321 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004322 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004323 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004324 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004325 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004326 visibleAccountTypes,
4327 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004328 } finally {
4329 restoreCallingIdentity(identityToken);
4330 }
4331 }
4332
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004333 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004334 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004335 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004336 int callingUid,
4337 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004338 List<String> visibleAccountTypes,
4339 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004340 ArrayList<Account> visibleAccounts = new ArrayList<>();
4341 for (String visibleType : visibleAccountTypes) {
4342 Account[] accountsForType = getAccountsFromCache(
4343 userAccounts, visibleType, callingUid, callingPackage,
4344 includeUserManagedNotVisible);
4345 if (accountsForType != null) {
4346 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004347 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004348 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004349 Account[] result = new Account[visibleAccounts.size()];
4350 for (int i = 0; i < visibleAccounts.size(); i++) {
4351 result[i] = visibleAccounts.get(i);
4352 }
4353 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004354 }
4355
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004356 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004357 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4358 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004359 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004360 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004361 for (Account account : accounts) {
4362 addSharedAccountAsUser(account, userId);
4363 }
4364 }
4365
4366 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004367 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004368 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004369 accounts.accountsDb.deleteSharedAccount(account);
4370 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004371 if (accountId < 0) {
4372 Log.w(TAG, "insertAccountIntoDatabase: " + account
4373 + ", skipping the DB insert failed");
4374 return false;
4375 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004376 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4377 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004378 return true;
4379 }
4380
4381 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004382 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4383 userId = handleIncomingUser(userId);
4384 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004385 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4386 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004387 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004388 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004389 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004390 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004391 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004392 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004393 }
4394 return r > 0;
4395 }
4396
4397 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004398 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004399 return removeSharedAccountAsUser(account, userId, getCallingUid());
4400 }
4401
4402 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004403 userId = handleIncomingUser(userId);
4404 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004405 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4406 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004407 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004408 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004409 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004410 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004411 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004412 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004413 }
4414
4415 @Override
4416 public Account[] getSharedAccountsAsUser(int userId) {
4417 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004418 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004419 synchronized (accounts.dbLock) {
4420 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4421 Account[] accountArray = new Account[accountList.size()];
4422 accountList.toArray(accountArray);
4423 return accountArray;
4424 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004425 }
4426
4427 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004428 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004429 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004430 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004431 }
4432
Amith Yamasani27db4682013-03-30 17:07:47 -07004433 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004434 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004435 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004436 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004437 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004438 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004439 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4440 + callingUid + " with uid=" + uid);
4441 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004442 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004443 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004444 }
4445
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004446 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004447 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004448 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4449 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004450 int callingUid = Binder.getCallingUid();
4451 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004452 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004453 int packageUid = -1;
4454 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004455 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4456 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004457 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004458 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004459 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004460 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004461 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4462 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004463 }
sunjiand62dc392017-06-01 12:05:59 -07004464 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) && type == null) {
4465 return getAccountsAsUserForPackage(type, userId,
4466 packageName, packageUid, opPackageName, false /* includeUserManagedNotVisible */);
4467 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004468 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004469 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004470 }
4471
sunjianf29d5492017-05-11 15:42:31 -07004472 private boolean needToStartChooseAccountActivity(Account[] accounts, String callingPackage) {
4473 if (accounts.length < 1) return false;
4474 if (accounts.length > 1) return true;
4475 Account account = accounts[0];
4476 UserAccounts userAccounts = getUserAccounts(UserHandle.getCallingUserId());
4477 int visibility = resolveAccountVisibility(account, callingPackage, userAccounts);
4478 if (visibility == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE) return true;
4479 return false;
4480 }
4481
4482 private void startChooseAccountActivityWithAccounts(
sunjianbdabd402017-06-06 17:54:07 -07004483 IAccountManagerResponse response, Account[] accounts, String callingPackage) {
sunjianf29d5492017-05-11 15:42:31 -07004484 Intent intent = new Intent(mContext, ChooseAccountActivity.class);
4485 intent.putExtra(AccountManager.KEY_ACCOUNTS, accounts);
4486 intent.putExtra(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE,
4487 new AccountManagerResponse(response));
sunjianbdabd402017-06-06 17:54:07 -07004488 intent.putExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004489
4490 mContext.startActivityAsUser(intent, UserHandle.of(UserHandle.getCallingUserId()));
4491 }
4492
4493 private void handleGetAccountsResult(
4494 IAccountManagerResponse response,
4495 Account[] accounts,
4496 String callingPackage) {
4497
4498 if (needToStartChooseAccountActivity(accounts, callingPackage)) {
sunjianbdabd402017-06-06 17:54:07 -07004499 startChooseAccountActivityWithAccounts(response, accounts, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004500 return;
4501 }
4502 if (accounts.length == 1) {
4503 Bundle bundle = new Bundle();
4504 bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accounts[0].name);
4505 bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accounts[0].type);
4506 onResult(response, bundle);
4507 return;
4508 }
4509 // No qualified account exists, return an empty Bundle.
4510 onResult(response, new Bundle());
4511 }
4512
4513 @Override
4514 public void getAccountByTypeAndFeatures(
4515 IAccountManagerResponse response,
4516 String accountType,
4517 String[] features,
4518 String opPackageName) {
4519
4520 int callingUid = Binder.getCallingUid();
4521 mAppOpsManager.checkPackage(callingUid, opPackageName);
4522 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4523 Log.v(TAG, "getAccount: accountType " + accountType
4524 + ", response " + response
4525 + ", features " + Arrays.toString(features)
4526 + ", caller's uid " + callingUid
4527 + ", pid " + Binder.getCallingPid());
4528 }
4529 if (response == null) throw new IllegalArgumentException("response is null");
4530 if (accountType == null) throw new IllegalArgumentException("accountType is null");
4531
4532 int userId = UserHandle.getCallingUserId();
4533
4534 long identityToken = clearCallingIdentity();
4535 try {
4536 UserAccounts userAccounts = getUserAccounts(userId);
4537 if (ArrayUtils.isEmpty(features)) {
4538 Account[] accountsWithManagedNotVisible = getAccountsFromCache(
4539 userAccounts, accountType, callingUid, opPackageName,
4540 true /* include managed not visible */);
4541 handleGetAccountsResult(
4542 response, accountsWithManagedNotVisible, opPackageName);
4543 return;
4544 }
4545
4546 IAccountManagerResponse retrieveAccountsResponse =
4547 new IAccountManagerResponse.Stub() {
4548 @Override
4549 public void onResult(Bundle value) throws RemoteException {
4550 Parcelable[] parcelables = value.getParcelableArray(
4551 AccountManager.KEY_ACCOUNTS);
4552 Account[] accounts = new Account[parcelables.length];
4553 for (int i = 0; i < parcelables.length; i++) {
4554 accounts[i] = (Account) parcelables[i];
4555 }
4556 handleGetAccountsResult(
4557 response, accounts, opPackageName);
4558 }
4559
4560 @Override
4561 public void onError(int errorCode, String errorMessage)
4562 throws RemoteException {
4563 // Will not be called in this case.
4564 }
4565 };
4566 new GetAccountsByTypeAndFeatureSession(
4567 userAccounts,
4568 retrieveAccountsResponse,
4569 accountType,
4570 features,
4571 callingUid,
4572 opPackageName,
4573 true /* include managed not visible */).bind();
4574 } finally {
4575 restoreCallingIdentity(identityToken);
4576 }
4577 }
4578
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004579 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004580 public void getAccountsByFeatures(
4581 IAccountManagerResponse response,
4582 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004583 String[] features,
4584 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004585 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004586 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004587 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4588 Log.v(TAG, "getAccounts: accountType " + type
4589 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004590 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004591 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004592 + ", pid " + Binder.getCallingPid());
4593 }
Fred Quintana382601f2010-03-25 12:25:10 -07004594 if (response == null) throw new IllegalArgumentException("response is null");
4595 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004596 int userId = UserHandle.getCallingUserId();
4597
Svetoslavf3f02ac2015-09-08 14:36:35 -07004598 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4599 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004600 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004601 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004602 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004603 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004604 try {
4605 response.onResult(result);
4606 } catch (RemoteException e) {
4607 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4608 }
4609 return;
4610 }
sunjianf29d5492017-05-11 15:42:31 -07004611
Fred Quintana33269202009-04-20 16:05:10 -07004612 long identityToken = clearCallingIdentity();
4613 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004614 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004615 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004616 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4617 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004618 Bundle result = new Bundle();
4619 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4620 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004621 return;
4622 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004623 new GetAccountsByTypeAndFeatureSession(
4624 userAccounts,
4625 response,
4626 type,
4627 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004628 callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004629 opPackageName,
4630 false /* include managed not visible */).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004631 } finally {
4632 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004633 }
4634 }
4635
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004636 @Override
4637 public void onAccountAccessed(String token) throws RemoteException {
4638 final int uid = Binder.getCallingUid();
4639 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4640 return;
4641 }
4642 final int userId = UserHandle.getCallingUserId();
4643 final long identity = Binder.clearCallingIdentity();
4644 try {
4645 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4646 if (Objects.equals(account.getAccessId(), token)) {
4647 // An app just accessed the account. At this point it knows about
4648 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004649 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004650 if (!hasAccountAccess(account, null, uid)) {
4651 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4652 uid, true);
4653 }
4654 }
4655 }
4656 } finally {
4657 Binder.restoreCallingIdentity(identity);
4658 }
4659 }
4660
Hongming Jin8e2bfc12018-05-30 11:01:06 -07004661 @Override
4662 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4663 FileDescriptor err, String[] args, ShellCallback callback,
4664 ResultReceiver resultReceiver) {
4665 new AccountManagerServiceShellCommand(this).exec(this, in, out, err, args,
4666 callback, resultReceiver);
4667 }
4668
Fred Quintanaa698f422009-04-08 19:14:54 -07004669 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004670 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004671 IAccountManagerResponse mResponse;
4672 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004673 final boolean mExpectActivityLaunch;
4674 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004675 final String mAccountName;
4676 // Indicates if we need to add auth details(like last credential time)
4677 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004678 // If set, we need to update the last authenticated time. This is
4679 // currently
4680 // used on
4681 // successful confirming credentials.
4682 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004683
Fred Quintana33269202009-04-20 16:05:10 -07004684 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004685 private int mNumRequestContinued = 0;
4686 private int mNumErrors = 0;
4687
Fred Quintana60307342009-03-24 22:48:12 -07004688 IAccountAuthenticator mAuthenticator = null;
4689
Fred Quintana8570f742010-02-18 10:32:54 -08004690 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004691 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004692
Amith Yamasani04e0d262012-02-14 11:50:53 -08004693 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004694 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4695 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004696 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4697 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4698 }
4699
4700 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4701 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4702 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004703 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004704 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004705 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004706 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004707 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004708 mResponse = response;
4709 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004710 mExpectActivityLaunch = expectActivityLaunch;
4711 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004712 mAccountName = accountName;
4713 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004714 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004715
Fred Quintanaa698f422009-04-08 19:14:54 -07004716 synchronized (mSessions) {
4717 mSessions.put(toString(), this);
4718 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004719 if (response != null) {
4720 try {
4721 response.asBinder().linkToDeath(this, 0 /* flags */);
4722 } catch (RemoteException e) {
4723 mResponse = null;
4724 binderDied();
4725 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004726 }
Fred Quintana60307342009-03-24 22:48:12 -07004727 }
4728
Fred Quintanaa698f422009-04-08 19:14:54 -07004729 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004730 if (mResponse == null) {
4731 // this session has already been closed
4732 return null;
4733 }
Fred Quintana60307342009-03-24 22:48:12 -07004734 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004735 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004736 return response;
4737 }
4738
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004739 /**
4740 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4741 * security policy.
4742 *
4743 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004744 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004745 * supplied entries in the system Settings app.
4746 */
tiansiminga8868bf2017-09-20 13:59:13 +08004747 protected boolean checkKeyIntent(int authUid, Intent intent) {
Jeff Sharkeyd722e782017-06-12 17:33:07 -06004748 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
4749 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
4750 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4751 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004752 long bid = Binder.clearCallingIdentity();
4753 try {
4754 PackageManager pm = mContext.getPackageManager();
4755 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
tiansiminga8868bf2017-09-20 13:59:13 +08004756 if (resolveInfo == null) {
4757 return false;
4758 }
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004759 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4760 int targetUid = targetActivityInfo.applicationInfo.uid;
Dan Cashman303c4bb2018-04-10 07:41:16 -07004761 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004762 if (!isExportedSystemActivity(targetActivityInfo)
Dan Cashman303c4bb2018-04-10 07:41:16 -07004763 && !pmi.hasSignatureCapability(
4764 targetUid, authUid,
4765 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004766 String pkgName = targetActivityInfo.packageName;
4767 String activityName = targetActivityInfo.name;
4768 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4769 + "does not share a signature with the supplying authenticator (%s).";
tiansiminga8868bf2017-09-20 13:59:13 +08004770 Log.e(TAG, String.format(tmpl, activityName, pkgName, mAccountType));
4771 return false;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004772 }
tiansiminga8868bf2017-09-20 13:59:13 +08004773 return true;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004774 } finally {
4775 Binder.restoreCallingIdentity(bid);
4776 }
4777 }
4778
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004779 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4780 String className = activityInfo.name;
4781 return "android".equals(activityInfo.packageName) &&
4782 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4783 || CantAddAccountActivity.class.getName().equals(className));
4784 }
4785
Fred Quintanaa698f422009-04-08 19:14:54 -07004786 private void close() {
4787 synchronized (mSessions) {
4788 if (mSessions.remove(toString()) == null) {
4789 // the session was already closed, so bail out now
4790 return;
4791 }
4792 }
4793 if (mResponse != null) {
4794 // stop listening for response deaths
4795 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4796
4797 // clear this so that we don't accidentally send any further results
4798 mResponse = null;
4799 }
4800 cancelTimeout();
4801 unbind();
4802 }
4803
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004804 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004805 public void binderDied() {
4806 mResponse = null;
4807 close();
4808 }
4809
4810 protected String toDebugString() {
4811 return toDebugString(SystemClock.elapsedRealtime());
4812 }
4813
4814 protected String toDebugString(long now) {
4815 return "Session: expectLaunch " + mExpectActivityLaunch
4816 + ", connected " + (mAuthenticator != null)
4817 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4818 + "/" + mNumErrors + ")"
4819 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4820 }
4821
Fred Quintana60307342009-03-24 22:48:12 -07004822 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004823 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4824 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4825 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004826 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004827 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004828 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004829 }
4830 }
4831
4832 private void unbind() {
4833 if (mAuthenticator != null) {
4834 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004835 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004836 }
4837 }
4838
Fred Quintana60307342009-03-24 22:48:12 -07004839 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004840 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004841 }
4842
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004843 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004844 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004845 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004846 try {
4847 run();
4848 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004849 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004850 "remote exception");
4851 }
Fred Quintana60307342009-03-24 22:48:12 -07004852 }
4853
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004854 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004855 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004856 mAuthenticator = null;
4857 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004858 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004859 try {
4860 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4861 "disconnected");
4862 } catch (RemoteException e) {
4863 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4864 Log.v(TAG, "Session.onServiceDisconnected: "
4865 + "caught RemoteException while responding", e);
4866 }
4867 }
Fred Quintana60307342009-03-24 22:48:12 -07004868 }
4869 }
4870
Fred Quintanab839afc2009-10-14 15:57:28 -07004871 public abstract void run() throws RemoteException;
4872
Fred Quintana60307342009-03-24 22:48:12 -07004873 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004874 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004875 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004876 try {
4877 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4878 "timeout");
4879 } catch (RemoteException e) {
4880 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4881 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4882 e);
4883 }
4884 }
Fred Quintana60307342009-03-24 22:48:12 -07004885 }
4886 }
4887
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004888 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004889 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004890 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004891 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004892 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004893 if (result != null) {
4894 boolean isSuccessfulConfirmCreds = result.getBoolean(
4895 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004896 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004897 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4898 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004899 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004900 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4901 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004902 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004903 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004904 if (needUpdate || mAuthDetailsRequired) {
4905 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4906 if (needUpdate && accountPresent) {
4907 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4908 }
4909 if (mAuthDetailsRequired) {
4910 long lastAuthenticatedTime = -1;
4911 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004912 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004913 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004914 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004915 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004916 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004917 lastAuthenticatedTime);
4918 }
4919 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004920 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004921 if (result != null
4922 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
tiansiminga8868bf2017-09-20 13:59:13 +08004923 if (!checkKeyIntent(
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004924 Binder.getCallingUid(),
tiansiminga8868bf2017-09-20 13:59:13 +08004925 intent)) {
4926 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
4927 "invalid intent in bundle returned");
4928 return;
4929 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004930 }
4931 if (result != null
4932 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004933 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4934 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004935 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4936 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004937 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4938 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004939 }
Fred Quintana60307342009-03-24 22:48:12 -07004940 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004941 IAccountManagerResponse response;
4942 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004943 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004944 response = mResponse;
4945 } else {
4946 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004947 }
Fred Quintana60307342009-03-24 22:48:12 -07004948 if (response != null) {
4949 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004950 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004951 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4952 Log.v(TAG, getClass().getSimpleName()
4953 + " calling onError() on response " + response);
4954 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004955 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004956 "null bundle returned");
4957 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004958 if (mStripAuthTokenFromResult) {
4959 result.remove(AccountManager.KEY_AUTHTOKEN);
4960 }
Fred Quintana56285a62010-12-02 14:20:51 -08004961 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4962 Log.v(TAG, getClass().getSimpleName()
4963 + " calling onResult() on response " + response);
4964 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004965 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4966 (intent == null)) {
4967 // All AccountManager error codes are greater than 0
4968 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4969 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4970 } else {
4971 response.onResult(result);
4972 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004973 }
Fred Quintana60307342009-03-24 22:48:12 -07004974 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004975 // if the caller is dead then there is no one to care about remote exceptions
4976 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4977 Log.v(TAG, "failure while notifying response", e);
4978 }
Fred Quintana60307342009-03-24 22:48:12 -07004979 }
4980 }
4981 }
Fred Quintana60307342009-03-24 22:48:12 -07004982
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004983 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004984 public void onRequestContinued() {
4985 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004986 }
4987
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004988 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004989 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004990 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004991 IAccountManagerResponse response = getResponseAndClose();
4992 if (response != null) {
4993 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004994 Log.v(TAG, getClass().getSimpleName()
4995 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004996 }
4997 try {
4998 response.onError(errorCode, errorMessage);
4999 } catch (RemoteException e) {
5000 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5001 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
5002 }
5003 }
5004 } else {
5005 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5006 Log.v(TAG, "Session.onError: already closed");
5007 }
Fred Quintana60307342009-03-24 22:48:12 -07005008 }
5009 }
Fred Quintanab839afc2009-10-14 15:57:28 -07005010
5011 /**
5012 * find the component name for the authenticator and initiate a bind
5013 * if no authenticator or the bind fails then return false, otherwise return true
5014 */
5015 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005016 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
5017 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
5018 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07005019 if (authenticatorInfo == null) {
5020 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5021 Log.v(TAG, "there is no authenticator for " + authenticatorType
5022 + ", bailing out");
5023 }
5024 return false;
5025 }
5026
Jeff Sharkeyce18c812016-04-27 16:00:41 -06005027 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06005028 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07005029 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
5030 + " which isn't encryption aware");
5031 return false;
5032 }
5033
Fred Quintanab839afc2009-10-14 15:57:28 -07005034 Intent intent = new Intent();
5035 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
5036 intent.setComponent(authenticatorInfo.componentName);
5037 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5038 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
5039 }
Hongming Jin8e2bfc12018-05-30 11:01:06 -07005040 int flags = Context.BIND_AUTO_CREATE;
5041 if (mAuthenticatorCache.getBindInstantServiceAllowed(mAccounts.userId)) {
5042 flags |= Context.BIND_ALLOW_INSTANT;
5043 }
5044 if (!mContext.bindServiceAsUser(intent, this, flags, UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07005045 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5046 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
5047 }
5048 return false;
5049 }
5050
Fred Quintanab839afc2009-10-14 15:57:28 -07005051 return true;
5052 }
Fred Quintana60307342009-03-24 22:48:12 -07005053 }
5054
Svet Ganov5d09c992016-09-07 09:57:41 -07005055 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07005056 MessageHandler(Looper looper) {
5057 super(looper);
5058 }
Costin Manolache3348f142009-09-29 18:58:36 -07005059
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07005060 @Override
Fred Quintana60307342009-03-24 22:48:12 -07005061 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07005062 switch (msg.what) {
5063 case MESSAGE_TIMED_OUT:
5064 Session session = (Session)msg.obj;
5065 session.onTimedOut();
5066 break;
5067
Amith Yamasani5be347b2013-03-31 17:44:31 -07005068 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00005069 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07005070 break;
5071
Fred Quintana60307342009-03-24 22:48:12 -07005072 default:
5073 throw new IllegalStateException("unhandled message: " + msg.what);
5074 }
5075 }
5076 }
5077
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005078 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005079 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005080 }
5081
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005082 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005083 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005084 }
5085
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005086 /*
5087 * This function receives an opened writable database.
5088 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005089 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005090 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005091 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005092 }
5093
5094 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005095 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005096 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005097 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005098 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005099
5100 class LogRecordTask implements Runnable {
5101 private final String action;
5102 private final String tableName;
5103 private final long accountId;
5104 private final UserAccounts userAccount;
5105 private final int callingUid;
5106 private final long userDebugDbInsertionPoint;
5107
5108 LogRecordTask(final String action,
5109 final String tableName,
5110 final long accountId,
5111 final UserAccounts userAccount,
5112 final int callingUid,
5113 final long userDebugDbInsertionPoint) {
5114 this.action = action;
5115 this.tableName = tableName;
5116 this.accountId = accountId;
5117 this.userAccount = userAccount;
5118 this.callingUid = callingUid;
5119 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
5120 }
5121
Andrew Scullc7770d62017-05-22 17:49:58 +01005122 @Override
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005123 public void run() {
5124 SQLiteStatement logStatement = userAccount.statementForLogging;
5125 logStatement.bindLong(1, accountId);
5126 logStatement.bindString(2, action);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005127 logStatement.bindString(3, mDateFormat.format(new Date()));
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005128 logStatement.bindLong(4, callingUid);
5129 logStatement.bindString(5, tableName);
5130 logStatement.bindLong(6, userDebugDbInsertionPoint);
Tetsutoki Shiozawabe2d96a2017-10-24 18:44:00 +09005131 try {
5132 logStatement.execute();
5133 } catch (IllegalStateException e) {
5134 // Guard against crash, DB can already be closed
5135 // since this statement is executed on a handler thread
5136 Slog.w(TAG, "Failed to insert a log record. accountId=" + accountId
5137 + " action=" + action + " tableName=" + tableName + " Error: " + e);
5138 } finally {
5139 logStatement.clearBindings();
5140 }
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005141 }
5142 }
5143
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07005144 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
5145 callingUid, userAccount.debugDbInsertionPoint);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005146 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005147 % AccountsDb.MAX_DEBUG_DB_SIZE;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07005148 mHandler.post(logTask);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005149 }
5150
5151 /*
5152 * This should only be called once to compile the sql statement for logging
5153 * and to find the insertion point.
5154 */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005155 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(UserAccounts userAccount) {
5156 userAccount.debugDbInsertionPoint = userAccount.accountsDb
5157 .calculateDebugTableInsertionPoint();
5158 userAccount.statementForLogging = userAccount.accountsDb.compileSqlStatementForLogging();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005159 }
5160
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005161 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005162 return asBinder();
5163 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005164
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005165 /**
5166 * Searches array of arguments for the specified string
5167 * @param args array of argument strings
5168 * @param value value to search for
5169 * @return true if the value is contained in the array
5170 */
5171 private static boolean scanArgs(String[] args, String value) {
5172 if (args != null) {
5173 for (String arg : args) {
5174 if (value.equals(arg)) {
5175 return true;
5176 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005177 }
5178 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005179 return false;
5180 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005181
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005182 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005183 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005184 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005185 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005186 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005187
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005188 final List<UserInfo> users = getUserManager().getUsers();
5189 for (UserInfo user : users) {
5190 ipw.println("User " + user + ":");
5191 ipw.increaseIndent();
5192 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5193 ipw.println();
5194 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005195 }
5196 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005197
Amith Yamasani04e0d262012-02-14 11:50:53 -08005198 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5199 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005200 if (isCheckinRequest) {
5201 // This is a checkin request. *Only* upload the account types and the count of
5202 // each.
5203 synchronized (userAccounts.dbLock) {
5204 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5205 }
5206 } else {
5207 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5208 Process.SYSTEM_UID, null /* packageName */, false);
5209 fout.println("Accounts: " + accounts.length);
5210 for (Account account : accounts) {
5211 fout.println(" " + account);
5212 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005213
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005214 // Add debug information.
5215 fout.println();
5216 synchronized (userAccounts.dbLock) {
5217 userAccounts.accountsDb.dumpDebugTable(fout);
5218 }
5219 fout.println();
5220 synchronized (mSessions) {
5221 final long now = SystemClock.elapsedRealtime();
5222 fout.println("Active Sessions: " + mSessions.size());
5223 for (Session session : mSessions.values()) {
5224 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005225 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005226 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005227
5228 fout.println();
5229 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Tony Mak6d14d772017-07-13 17:49:46 +08005230
5231 boolean isUserUnlocked;
5232 synchronized (mUsers) {
5233 isUserUnlocked = isLocalUnlockedUser(userAccounts.userId);
5234 }
5235 // Following logs are printed only when user is unlocked.
5236 if (!isUserUnlocked) {
5237 return;
5238 }
5239 fout.println();
5240 synchronized (userAccounts.dbLock) {
5241 Map<Account, Map<String, Integer>> allVisibilityValues =
5242 userAccounts.accountsDb.findAllVisibilityValues();
5243 fout.println("Account visibility:");
5244 for (Account account : allVisibilityValues.keySet()) {
5245 fout.println(" " + account.name);
5246 Map<String, Integer> visibilities = allVisibilityValues.get(account);
5247 for (Entry<String, Integer> entry : visibilities.entrySet()) {
5248 fout.println(" " + entry.getKey() + ", " + entry.getValue());
5249 }
5250 }
5251 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005252 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005253 }
5254
Amith Yamasani04e0d262012-02-14 11:50:53 -08005255 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005256 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005257 long identityToken = clearCallingIdentity();
5258 try {
5259 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5260 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5261 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005262
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005263 if (intent.getComponent() != null &&
5264 GrantCredentialsPermissionActivity.class.getName().equals(
5265 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005266 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005267 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005268 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005269 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5270 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005271
Fred Quintana33f889a2009-09-14 17:31:26 -07005272 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005273 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005274 Notification n =
5275 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005276 .setWhen(0)
5277 .setSmallIcon(android.R.drawable.stat_sys_warning)
5278 .setColor(contextForUser.getColor(
5279 com.android.internal.R.color.system_notification_accent_color))
5280 .setContentTitle(String.format(notificationTitleFormat, account.name))
5281 .setContentText(message)
5282 .setContentIntent(PendingIntent.getActivityAsUser(
5283 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005284 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005285 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005286 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005287 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005288 } finally {
5289 restoreCallingIdentity(identityToken);
5290 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005291 }
5292
Chris Wren717a8812017-03-31 15:34:39 -04005293 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005294 String packageName, int userId) {
5295 final long token = clearCallingIdentity();
5296 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005297 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005298 try {
Chris Wren717a8812017-03-31 15:34:39 -04005299 notificationManager.enqueueNotificationWithTag(packageName, packageName,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005300 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005301 } catch (RemoteException e) {
5302 /* ignore - local call */
5303 }
5304 } finally {
5305 Binder.restoreCallingIdentity(token);
5306 }
Fred Quintana56285a62010-12-02 14:20:51 -08005307 }
5308
Chris Wren717a8812017-03-31 15:34:39 -04005309 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005310 cancelNotification(id, mContext.getPackageName(), user);
5311 }
5312
Chris Wren717a8812017-03-31 15:34:39 -04005313 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005314 long identityToken = clearCallingIdentity();
5315 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005316 INotificationManager service = mInjector.getNotificationManager();
Chris Wren717a8812017-03-31 15:34:39 -04005317 service.cancelNotificationWithTag(packageName, id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005318 } catch (RemoteException e) {
5319 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005320 } finally {
5321 restoreCallingIdentity(identityToken);
5322 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005323 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005324
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005325 private boolean isPermittedForPackage(String packageName, int uid, int userId,
5326 String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005327 final long identity = Binder.clearCallingIdentity();
5328 try {
5329 IPackageManager pm = ActivityThread.getPackageManager();
5330 for (String perm : permissions) {
5331 if (pm.checkPermission(perm, packageName, userId)
5332 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005333 // Checks runtime permission revocation.
5334 final int opCode = AppOpsManager.permissionToOpCode(perm);
Tony Mak58f28152017-09-20 21:23:48 +01005335 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005336 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5337 return true;
5338 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005339 }
5340 }
5341 } catch (RemoteException e) {
5342 /* ignore - local call */
5343 } finally {
5344 Binder.restoreCallingIdentity(identity);
5345 }
5346 return false;
5347 }
5348
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005349 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5350 for (String perm : permissions) {
5351 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5352 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5353 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5354 }
5355 final int opCode = AppOpsManager.permissionToOpCode(perm);
Tony Mak58f28152017-09-20 21:23:48 +01005356 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005357 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5358 return true;
5359 }
5360 }
5361 }
5362 return false;
5363 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005364
Amith Yamasani67df64b2012-12-14 12:09:36 -08005365 private int handleIncomingUser(int userId) {
5366 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005367 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005368 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5369 } catch (RemoteException re) {
5370 // Shouldn't happen, local.
5371 }
5372 return userId;
5373 }
5374
Christopher Tateccbf84f2013-05-08 15:25:41 -07005375 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005376 String[] packages;
5377 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005378 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005379 packages = mPackageManager.getPackagesForUid(callingUid);
sunjian9ae597b62017-08-14 15:45:04 -07005380 if (packages == null) {
5381 Log.d(TAG, "No packages for callingUid " + callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005382 return false;
5383 }
sunjian9ae597b62017-08-14 15:45:04 -07005384 for (String name : packages) {
5385 try {
5386 PackageInfo packageInfo =
5387 mPackageManager.getPackageInfo(name, 0 /* flags */);
5388 if (packageInfo != null
5389 && (packageInfo.applicationInfo.privateFlags
5390 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5391 return true;
5392 }
5393 } catch (PackageManager.NameNotFoundException e) {
5394 Log.d(TAG, "Package not found " + e.getMessage());
5395 }
5396 }
5397 } finally {
5398 Binder.restoreCallingIdentity(identityToken);
Fred Quintana7be59642009-08-24 18:29:25 -07005399 }
5400 return false;
5401 }
5402
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005403 private boolean permissionIsGranted(
5404 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005405 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5406 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5407 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5408 }
5409 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005410 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005411
5412 if (isPrivileged(callerUid)) {
5413 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5414 Log.v(TAG, "Access to " + account + " granted calling uid "
5415 + callerUid + " privileged");
5416 }
5417 return true;
5418 }
5419 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5420 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5421 Log.v(TAG, "Access to " + account + " granted calling uid "
5422 + callerUid + " manages the account");
5423 }
5424 return true;
5425 }
5426 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5427 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5428 Log.v(TAG, "Access to " + account + " granted calling uid "
5429 + callerUid + " user granted access");
5430 }
5431 return true;
5432 }
5433
5434 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5435 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5436 }
5437
5438 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005439 }
5440
Svetoslavf3f02ac2015-09-08 14:36:35 -07005441 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5442 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005443 if (accountType == null) {
5444 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005445 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005446 return getTypesVisibleToCaller(callingUid, userId,
5447 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005448 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005449 }
5450
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005451 // Method checks visibility for applications targeing API level below {@link
5452 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005453 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005454 private boolean checkGetAccountsPermission(String packageName, int uid, int userId) {
5455 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005456 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5457 }
5458
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005459 private boolean checkReadContactsPermission(String packageName, int uid, int userId) {
5460 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.READ_CONTACTS);
5461 }
5462
5463 // Heuristic to check that account type may be associated with some contacts data and
5464 // therefore READ_CONTACTS permission grants the access to account by default.
5465 private boolean accountTypeManagesContacts(String accountType, int userId) {
5466 if (accountType == null) {
5467 return false;
5468 }
5469 long identityToken = Binder.clearCallingIdentity();
5470 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5471 try {
5472 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5473 } finally {
5474 Binder.restoreCallingIdentity(identityToken);
5475 }
5476 // Check contacts related permissions for authenticator.
5477 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5478 : serviceInfos) {
5479 if (accountType.equals(serviceInfo.type.type)) {
5480 return isPermittedForPackage(serviceInfo.type.packageName, serviceInfo.uid, userId,
5481 Manifest.permission.WRITE_CONTACTS);
5482 }
5483 }
5484 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005485 }
5486
5487 /**
5488 * Method checks package uid and signature with Authenticator which manages accountType.
5489 *
5490 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5491 * SIGNATURE_CHECK_MISMATCH otherwise.
5492 */
5493 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5494 if (accountType == null) {
5495 return SIGNATURE_CHECK_MISMATCH;
5496 }
5497
5498 long identityToken = Binder.clearCallingIdentity();
5499 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5500 try {
5501 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5502 } finally {
5503 Binder.restoreCallingIdentity(identityToken);
5504 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005505 // Check for signature match with Authenticator.LocalServices.getService(PackageManagerInternal.class);
5506 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005507 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5508 : serviceInfos) {
5509 if (accountType.equals(serviceInfo.type.type)) {
5510 if (serviceInfo.uid == callingUid) {
5511 return SIGNATURE_CHECK_UID_MATCH;
5512 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005513 if (pmi.hasSignatureCapability(
5514 serviceInfo.uid, callingUid,
5515 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005516 return SIGNATURE_CHECK_MATCH;
5517 }
5518 }
5519 }
5520 return SIGNATURE_CHECK_MISMATCH;
5521 }
5522
5523 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005524 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5525 if (accountType == null) {
5526 return false;
5527 } else {
5528 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5529 }
5530 }
5531
Svetoslavf3f02ac2015-09-08 14:36:35 -07005532 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5533 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005534 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005535 }
5536
5537 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005538 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005539 }
5540
5541 private List<String> getTypesForCaller(
5542 int callingUid, int userId, boolean isOtherwisePermitted) {
5543 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005544 long identityToken = Binder.clearCallingIdentity();
5545 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5546 try {
5547 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5548 } finally {
5549 Binder.restoreCallingIdentity(identityToken);
5550 }
Dan Cashman303c4bb2018-04-10 07:41:16 -07005551
5552 PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005553 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005554 serviceInfos) {
Dan Cashman303c4bb2018-04-10 07:41:16 -07005555 if (isOtherwisePermitted || pmi.hasSignatureCapability(
5556 serviceInfo.uid, callingUid,
5557 PackageParser.SigningDetails.CertCapabilities.AUTH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005558 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005559 }
5560 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005561 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005562 }
5563
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005564 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5565 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5566 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5567 if (account.name.equals(accountName)) {
5568 return true;
5569 }
5570 }
5571 }
5572 return false;
5573 }
5574
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005575 private static void checkManageUsersPermission(String message) {
5576 if (ActivityManager.checkComponentPermission(
5577 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5578 != PackageManager.PERMISSION_GRANTED) {
5579 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5580 }
5581 }
5582
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005583 private static void checkManageOrCreateUsersPermission(String message) {
5584 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5585 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5586 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5587 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5588 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5589 + message);
5590 }
5591 }
5592
Amith Yamasani04e0d262012-02-14 11:50:53 -08005593 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5594 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005595 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005596 return true;
5597 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005598 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005599 synchronized (accounts.dbLock) {
5600 synchronized (accounts.cacheLock) {
5601 long grantsCount;
5602 if (authTokenType != null) {
5603 grantsCount = accounts.accountsDb
5604 .findMatchingGrantsCount(callerUid, authTokenType, account);
5605 } else {
5606 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5607 account);
5608 }
5609 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005610
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005611 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5612 // TODO: Skip this check when running automated tests. Replace this
5613 // with a more general solution.
5614 Log.d(TAG, "no credentials permission for usage of " + account + ", "
5615 + authTokenType + " by uid " + callerUid
5616 + " but ignoring since device is in test harness.");
5617 return true;
5618 }
5619 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005620 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005621 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005622 }
5623
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005624 private boolean isSystemUid(int callingUid) {
5625 String[] packages = null;
5626 long ident = Binder.clearCallingIdentity();
5627 try {
5628 packages = mPackageManager.getPackagesForUid(callingUid);
Alex Chau81a47cd2018-01-02 16:49:14 +00005629 if (packages != null) {
5630 for (String name : packages) {
5631 try {
5632 PackageInfo packageInfo =
5633 mPackageManager.getPackageInfo(name, 0 /* flags */);
5634 if (packageInfo != null
5635 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5636 != 0) {
5637 return true;
5638 }
5639 } catch (NameNotFoundException e) {
5640 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5641 }
5642 }
5643 } else {
5644 Log.w(TAG, "No known packages with uid " + callingUid);
5645 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005646 } finally {
5647 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005648 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005649 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005650 }
5651
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005652 /** Succeeds if any of the specified permissions are granted. */
5653 private void checkReadAccountsPermitted(
5654 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005655 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005656 int userId,
5657 String opPackageName) {
5658 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005659 String msg = String.format(
5660 "caller uid %s cannot access %s accounts",
5661 callingUid,
5662 accountType);
5663 Log.w(TAG, " " + msg);
5664 throw new SecurityException(msg);
5665 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005666 }
5667
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005668 private boolean canUserModifyAccounts(int userId, int callingUid) {
5669 // the managing app can always modify accounts
5670 if (isProfileOwner(callingUid)) {
5671 return true;
5672 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005673 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5674 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5675 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005676 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005677 return true;
5678 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005679
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005680 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5681 // the managing app can always modify accounts
5682 if (isProfileOwner(callingUid)) {
5683 return true;
5684 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005685 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5686 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005687 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005688 if (typesArray == null) {
5689 return true;
5690 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005691 for (String forbiddenType : typesArray) {
5692 if (forbiddenType.equals(accountType)) {
5693 return false;
5694 }
5695 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005696 return true;
5697 }
5698
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005699 private boolean isProfileOwner(int uid) {
5700 final DevicePolicyManagerInternal dpmi =
5701 LocalServices.getService(DevicePolicyManagerInternal.class);
5702 return (dpmi != null)
5703 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5704 }
5705
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005706 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005707 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5708 throws RemoteException {
5709 final int callingUid = getCallingUid();
5710
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005711 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005712 throw new SecurityException();
5713 }
5714
5715 if (value) {
5716 grantAppPermission(account, authTokenType, uid);
5717 } else {
5718 revokeAppPermission(account, authTokenType, uid);
5719 }
5720 }
5721
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005722 /**
5723 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5724 * <p>
5725 * Although this is public it can only be accessed via the AccountManagerService object
5726 * which is in the system. This means we don't need to protect it with permissions.
5727 * @hide
5728 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005729 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005730 if (account == null || authTokenType == null) {
5731 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005732 return;
5733 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005734 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005735 synchronized (accounts.dbLock) {
5736 synchronized (accounts.cacheLock) {
5737 long accountId = accounts.accountsDb.findDeAccountId(account);
5738 if (accountId >= 0) {
5739 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5740 }
5741 cancelNotification(
5742 getCredentialPermissionNotificationId(account, authTokenType, uid),
5743 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005744
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005745 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5746 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005747 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005748
5749 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5750 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5751 : mAppPermissionChangeListeners) {
5752 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5753 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005754 }
5755
5756 /**
5757 * Don't allow callers with the given uid permission to get credentials for
5758 * account/authTokenType.
5759 * <p>
5760 * Although this is public it can only be accessed via the AccountManagerService object
5761 * which is in the system. This means we don't need to protect it with permissions.
5762 * @hide
5763 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005764 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005765 if (account == null || authTokenType == null) {
5766 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005767 return;
5768 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005769 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005770 synchronized (accounts.dbLock) {
5771 synchronized (accounts.cacheLock) {
5772 accounts.accountsDb.beginTransaction();
5773 try {
5774 long accountId = accounts.accountsDb.findDeAccountId(account);
5775 if (accountId >= 0) {
5776 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5777 accountId, authTokenType, uid);
5778 accounts.accountsDb.setTransactionSuccessful();
5779 }
5780 } finally {
5781 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005782 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005783
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005784 cancelNotification(
5785 getCredentialPermissionNotificationId(account, authTokenType, uid),
5786 UserHandle.of(accounts.userId));
5787 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005788 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005789
5790 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5791 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5792 : mAppPermissionChangeListeners) {
5793 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5794 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005795 }
Fred Quintana56285a62010-12-02 14:20:51 -08005796
Amith Yamasani04e0d262012-02-14 11:50:53 -08005797 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5798 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005799 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005800 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005801 for (Account curAccount : oldAccountsForType) {
5802 if (!curAccount.equals(account)) {
5803 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005804 }
5805 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005806 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005807 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005808 } else {
5809 Account[] newAccountsForType = new Account[newAccountsList.size()];
5810 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005811 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005812 }
Fred Quintana56285a62010-12-02 14:20:51 -08005813 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005814 accounts.userDataCache.remove(account);
5815 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005816 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005817 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005818 }
5819
5820 /**
5821 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005822 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5823 * processes and if you will return this account to apps you should return the result.
5824 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005825 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005826 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005827 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005828 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5829 Account[] newAccountsForType = new Account[oldLength + 1];
5830 if (accountsForType != null) {
5831 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005832 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005833 String token = account.getAccessId() != null ? account.getAccessId()
5834 : UUID.randomUUID().toString();
5835 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005836 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005837 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005838 }
5839
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005840 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005841 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005842 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005843 String visibilityFilterPackage = callingPackage;
5844 if (visibilityFilterPackage == null) {
5845 visibilityFilterPackage = getPackageNameForUid(callingUid);
5846 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005847 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005848 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005849 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005850 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5851 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5852 || (includeManagedNotVisible
5853 && (visibility
5854 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5855 firstPass.put(account, visibility);
5856 }
5857 }
5858 Map<Account, Integer> secondPass =
5859 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5860
5861 Account[] filtered = new Account[secondPass.size()];
5862 filtered = secondPass.keySet().toArray(filtered);
5863 return filtered;
5864 }
5865
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005866 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005867 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005868 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005869 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005870 // first part is to filter shared accounts.
5871 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005872 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005873 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005874 return unfiltered;
5875 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005876 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005877 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005878 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005879 if (packages == null) {
5880 packages = new String[] {};
5881 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005882 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005883 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005884 // This might be a temporary way to specify a visible list
5885 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005886 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5887 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005888 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005889 return unfiltered;
5890 }
5891 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005892 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005893 if (ArrayUtils.isEmpty(sharedAccounts)) {
5894 return unfiltered;
5895 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005896 String requiredAccountType = "";
5897 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005898 // If there's an explicit callingPackage specified, check if that package
5899 // opted in to see restricted accounts.
5900 if (callingPackage != null) {
5901 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005902 if (pi != null && pi.restrictedAccountType != null) {
5903 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005904 }
5905 } else {
5906 // Otherwise check if the callingUid has a package that has opted in
5907 for (String packageName : packages) {
5908 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5909 if (pi != null && pi.restrictedAccountType != null) {
5910 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005911 break;
5912 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005913 }
5914 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005915 } catch (NameNotFoundException e) {
5916 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005917 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005918 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005919 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5920 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005921 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005922 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005923 } else {
5924 boolean found = false;
5925 for (Account shared : sharedAccounts) {
5926 if (shared.equals(account)) {
5927 found = true;
5928 break;
5929 }
5930 }
5931 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005932 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005933 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005934 }
5935 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005936 return filtered;
5937 } else {
5938 return unfiltered;
5939 }
5940 }
5941
Amith Yamasani27db4682013-03-30 17:07:47 -07005942 /*
5943 * packageName can be null. If not null, it should be used to filter out restricted accounts
5944 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005945 *
5946 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5947 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005948 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005949 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005950 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005951 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005952 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5953 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005954 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005955 Account[] accounts;
5956 synchronized (userAccounts.cacheLock) {
5957 accounts = userAccounts.accountCache.get(accountType);
5958 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005959 if (accounts == null) {
5960 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005961 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005962 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5963 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005964 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005965 } else {
5966 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005967 Account[] accountsArray;
5968 synchronized (userAccounts.cacheLock) {
5969 for (Account[] accounts : userAccounts.accountCache.values()) {
5970 totalLength += accounts.length;
5971 }
5972 if (totalLength == 0) {
5973 return EMPTY_ACCOUNT_ARRAY;
5974 }
5975 accountsArray = new Account[totalLength];
5976 totalLength = 0;
5977 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5978 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5979 accountsOfType.length);
5980 totalLength += accountsOfType.length;
5981 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005982 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005983 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005984 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005985 }
5986 }
5987
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005988 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005989 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005990 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005991 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005992 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005993 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005994 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005995 }
5996 if (value == null) {
5997 userDataForAccount.remove(key);
5998 } else {
5999 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08006000 }
6001 }
6002
Carlos Valdivia91979be2015-05-22 14:11:35 -07006003 protected String readCachedTokenInternal(
6004 UserAccounts accounts,
6005 Account account,
6006 String tokenType,
6007 String callingPackage,
6008 byte[] pkgSigDigest) {
Dmitry Dementyev18f0ca92017-06-12 17:56:47 -07006009 synchronized (accounts.cacheLock) {
6010 return accounts.accountTokenCaches.get(
6011 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07006012 }
6013 }
6014
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006015 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006016 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08006017 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006018 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006019 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07006020 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08006021 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08006022 }
6023 if (value == null) {
6024 authTokensForAccount.remove(key);
6025 } else {
6026 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08006027 }
6028 }
6029
Amith Yamasani04e0d262012-02-14 11:50:53 -08006030 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
6031 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07006032 // Fast path - check if account is already cached
6033 synchronized (accounts.cacheLock) {
6034 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
6035 if (authTokensForAccount != null) {
6036 return authTokensForAccount.get(authTokenType);
6037 }
6038 }
6039 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07006040 synchronized (accounts.dbLock) {
6041 synchronized (accounts.cacheLock) {
6042 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
6043 if (authTokensForAccount == null) {
6044 // need to populate the cache for this account
6045 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
6046 accounts.authTokenCache.put(account, authTokensForAccount);
6047 }
6048 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08006049 }
Fred Quintana56285a62010-12-02 14:20:51 -08006050 }
6051 }
6052
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006053 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
6054 Map<String, String> userDataForAccount;
6055 // Fast path - check if data is already cached
6056 synchronized (accounts.cacheLock) {
6057 userDataForAccount = accounts.userDataCache.get(account);
6058 }
6059 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00006060 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006061 synchronized (accounts.dbLock) {
6062 synchronized (accounts.cacheLock) {
6063 userDataForAccount = accounts.userDataCache.get(account);
6064 if (userDataForAccount == null) {
6065 // need to populate the cache for this account
6066 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
6067 accounts.userDataCache.put(account, userDataForAccount);
6068 }
6069 }
6070 }
Fred Quintana56285a62010-12-02 14:20:51 -08006071 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00006072 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08006073 }
6074
Kenny Guy07ad8dc2014-09-01 20:56:12 +01006075 private Context getContextForUser(UserHandle user) {
6076 try {
6077 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
6078 } catch (NameNotFoundException e) {
6079 // Default to mContext, not finding the package system is running as is unlikely.
6080 return mContext;
6081 }
6082 }
Sandra Kwan78812282015-11-04 11:19:47 -08006083
6084 private void sendResponse(IAccountManagerResponse response, Bundle result) {
6085 try {
6086 response.onResult(result);
6087 } catch (RemoteException e) {
6088 // if the caller is dead then there is no one to care about remote
6089 // exceptions
6090 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6091 Log.v(TAG, "failure while notifying response", e);
6092 }
6093 }
6094 }
6095
6096 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
6097 String errorMessage) {
6098 try {
6099 response.onError(errorCode, errorMessage);
6100 } catch (RemoteException e) {
6101 // if the caller is dead then there is no one to care about remote
6102 // exceptions
6103 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6104 Log.v(TAG, "failure while notifying response", e);
6105 }
6106 }
6107 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006108
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006109 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07006110 private final Object mLock = new Object();
6111
6112 @GuardedBy("mLock")
6113 private AccountManagerBackupHelper mBackupHelper;
6114
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006115 @Override
6116 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
6117 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
6118 if (account == null) {
6119 Slog.w(TAG, "account cannot be null");
6120 return;
6121 }
6122 if (packageName == null) {
6123 Slog.w(TAG, "packageName cannot be null");
6124 return;
6125 }
6126 if (userId < UserHandle.USER_SYSTEM) {
6127 Slog.w(TAG, "user id must be concrete");
6128 return;
6129 }
6130 if (callback == null) {
6131 Slog.w(TAG, "callback cannot be null");
6132 return;
6133 }
6134
Dmitry Dementyev7b3ea132017-05-10 12:45:02 -07006135 int visibility =
6136 resolveAccountVisibility(account, packageName, getUserAccounts(userId));
6137 if (visibility == AccountManager.VISIBILITY_NOT_VISIBLE) {
6138 Slog.w(TAG, "requestAccountAccess: account is hidden");
6139 return;
6140 }
6141
Svet Ganovf6d424f12016-09-20 20:18:53 -07006142 if (AccountManagerService.this.hasAccountAccess(account, packageName,
6143 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006144 Bundle result = new Bundle();
6145 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
6146 callback.sendResult(result);
6147 return;
6148 }
6149
6150 final int uid;
6151 try {
6152 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
6153 } catch (NameNotFoundException e) {
6154 Slog.e(TAG, "Unknown package " + packageName);
6155 return;
6156 }
6157
6158 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006159 final UserAccounts userAccounts;
6160 synchronized (mUsers) {
6161 userAccounts = mUsers.get(userId);
6162 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04006163 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006164 doNotification(userAccounts, account, null, intent, packageName, userId);
6165 }
6166
6167 @Override
6168 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
6169 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
6170 mAppPermissionChangeListeners.add(listener);
6171 }
6172
6173 @Override
6174 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
6175 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006176 }
Svet Ganov5d09c992016-09-07 09:57:41 -07006177
6178 @Override
6179 public byte[] backupAccountAccessPermissions(int userId) {
6180 synchronized (mLock) {
6181 if (mBackupHelper == null) {
6182 mBackupHelper = new AccountManagerBackupHelper(
6183 AccountManagerService.this, this);
6184 }
6185 return mBackupHelper.backupAccountAccessPermissions(userId);
6186 }
6187 }
6188
6189 @Override
6190 public void restoreAccountAccessPermissions(byte[] data, int userId) {
6191 synchronized (mLock) {
6192 if (mBackupHelper == null) {
6193 mBackupHelper = new AccountManagerBackupHelper(
6194 AccountManagerService.this, this);
6195 }
6196 mBackupHelper.restoreAccountAccessPermissions(data, userId);
6197 }
6198 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006199 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07006200
6201 @VisibleForTesting
6202 static class Injector {
6203 private final Context mContext;
6204
6205 public Injector(Context context) {
6206 mContext = context;
6207 }
6208
6209 Looper getMessageHandlerLooper() {
6210 ServiceThread serviceThread = new ServiceThread(TAG,
6211 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
6212 serviceThread.start();
6213 return serviceThread.getLooper();
6214 }
6215
6216 Context getContext() {
6217 return mContext;
6218 }
6219
6220 void addLocalService(AccountManagerInternal service) {
6221 LocalServices.addService(AccountManagerInternal.class, service);
6222 }
6223
6224 String getDeDatabaseName(int userId) {
6225 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
6226 AccountsDb.DE_DATABASE_NAME);
6227 return databaseFile.getPath();
6228 }
6229
6230 String getCeDatabaseName(int userId) {
6231 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6232 AccountsDb.CE_DATABASE_NAME);
6233 return databaseFile.getPath();
6234 }
6235
6236 String getPreNDatabaseName(int userId) {
6237 File systemDir = Environment.getDataSystemDirectory();
6238 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6239 PRE_N_DATABASE_NAME);
6240 if (userId == 0) {
6241 // Migrate old file, if it exists, to the new location.
6242 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006243 // accidentally created in the old location,
6244 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006245 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6246 if (oldFile.exists() && !databaseFile.exists()) {
6247 // Check for use directory; create if it doesn't exist, else renameTo will fail
6248 File userDir = Environment.getUserSystemDirectory(userId);
6249 if (!userDir.exists()) {
6250 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006251 throw new IllegalStateException(
6252 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006253 }
6254 }
6255 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006256 throw new IllegalStateException(
6257 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006258 }
6259 }
6260 }
6261 return databaseFile.getPath();
6262 }
6263
6264 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6265 return new AccountAuthenticatorCache(mContext);
6266 }
6267
6268 INotificationManager getNotificationManager() {
6269 return NotificationManager.getService();
6270 }
6271 }
Chris Wren717a8812017-03-31 15:34:39 -04006272
Andrew Scullc7770d62017-05-22 17:49:58 +01006273 private static class NotificationId {
Chris Wren717a8812017-03-31 15:34:39 -04006274 final String mTag;
6275 private final int mId;
6276
6277 NotificationId(String tag, int type) {
6278 mTag = tag;
6279 mId = type;
6280 }
6281 }
Fred Quintana60307342009-03-24 22:48:12 -07006282}