1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (c) 2014-2017, The Linux Foundation.
*/
/*
* Copyright 2012 Giesecke & Devrient GmbH.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.se.security;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Build;
import android.os.SystemProperties;
import android.util.Log;
import com.android.se.Channel;
import com.android.se.SecureElementService;
import com.android.se.Terminal;
import com.android.se.internal.ByteArrayConverter;
import com.android.se.security.ChannelAccess.ACCESS;
import com.android.se.security.ara.AraController;
import com.android.se.security.arf.ArfController;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.AccessControlException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.NoSuchElementException;
/** Reads and Maintains the ARF and ARA access control for a particular Secure Element */
public class AccessControlEnforcer {
private final String mTag = "SecureElement-AccessControlEnforcer";
private static final boolean DEBUG = Build.IS_DEBUGGABLE;
private PackageManager mPackageManager = null;
private boolean mNoRuleFound = false;
private AraController mAraController = null;
private boolean mUseAra = true;
private ArfController mArfController = null;
private boolean mUseArf = false;
private AccessRuleCache mAccessRuleCache = null;
private boolean mRulesRead = false;
private Terminal mTerminal = null;
private ChannelAccess mInitialChannelAccess = new ChannelAccess();
private boolean mFullAccess = false;
public AccessControlEnforcer(Terminal terminal) {
mTerminal = terminal;
mAccessRuleCache = new AccessRuleCache();
}
public byte[] getDefaultAccessControlAid() {
if (mAraController != null) {
return mAraController.getAccessControlAid();
}
return AraController.getAraMAid();
}
public PackageManager getPackageManager() {
return mPackageManager;
}
public void setPackageManager(PackageManager packageManager) {
mPackageManager = packageManager;
}
public Terminal getTerminal() {
return mTerminal;
}
public AccessRuleCache getAccessRuleCache() {
return mAccessRuleCache;
}
/** Resets the Access Control for the Secure Element */
public synchronized void reset() {
// Destroy any previous Controler
// in order to reset the ACE
Log.i(mTag, "Reset the ACE for terminal:" + mTerminal.getName());
mAccessRuleCache.reset();
mAraController = null;
mArfController = null;
}
/** Initializes the Access Control for the Secure Element */
public synchronized void initialize() throws IOException, MissingResourceException {
boolean status = true;
String denyMsg = "";
// allow access to set up access control for a channel
mInitialChannelAccess.setApduAccess(ChannelAccess.ACCESS.ALLOWED);
mInitialChannelAccess.setNFCEventAccess(ChannelAccess.ACCESS.ALLOWED);
mInitialChannelAccess.setAccess(ChannelAccess.ACCESS.ALLOWED, "");
readSecurityProfile();
mNoRuleFound = false;
// 1 - Let's try to use ARA
if (mUseAra && mAraController == null) {
mAraController = new AraController(mAccessRuleCache, mTerminal);
}
if (mUseAra && mAraController != null) {
try {
mAraController.initialize();
Log.i(mTag, "ARA applet is used for:" + mTerminal.getName());
// disable other access methods
mUseArf = false;
mFullAccess = false;
} catch (IOException | MissingResourceException e) {
throw e;
} catch (Exception e) {
// ARA cannot be used since we got an exception during initialization
mUseAra = false;
denyMsg = e.getLocalizedMessage();
if (e instanceof NoSuchElementException) {
Log.i(mTag, "No ARA applet found in: " + mTerminal.getName());
if (!mUseArf) {
// ARA does not exist on the secure element right now,
// but it might be installed later.
mNoRuleFound = true;
status = mFullAccess;
}
} else if (mTerminal.getName().startsWith(SecureElementService.UICC_TERMINAL)) {
// A possible explanation could simply be due to the fact that the UICC is old
// and does not support logical channel (and is not compliant with GP spec).
// We should simply act as if no ARA was available in this case.
if (!mUseArf) {
// Only ARA was the candidate to retrieve access rules,
// but it is not 100% sure if the expected ARA really does not exist.
// Full access should not be granted in this case.
mFullAccess = false;
status = false;
}
} else {
// ARA is available but doesn't work properly.
// We are going to disable everything per security req.
mUseArf = false;
mFullAccess = false;
status = false;
Log.i(mTag, "Problem accessing ARA, Access DENIED "
+ e.getLocalizedMessage());
}
}
}
// 2 - Let's try to use ARF since ARA cannot be used
if (mUseArf && mArfController == null) {
mArfController = new ArfController(mAccessRuleCache, mTerminal);
}
if (mUseArf && mArfController != null) {
try {
mArfController.initialize();
// disable other access methods
Log.i(mTag, "ARF rules are used for:" + mTerminal.getName());
mFullAccess = false;
} catch (IOException | MissingResourceException e) {
throw e;
} catch (Exception e) {
// ARF cannot be used since we got an exception
mUseArf = false;
denyMsg = e.getLocalizedMessage();
Log.e(mTag, e.getMessage());
if (e instanceof NoSuchElementException) {
Log.i(mTag, "No ARF found in: " + mTerminal.getName());
// ARF does not exist on the secure element right now,
// but it might be added later.
mNoRuleFound = true;
status = mFullAccess;
} else {
// It is not 100% sure if the expected ARF really does not exist.
// No ARF might be due to a kind of temporary problem,
// so full access should not be granted in this case.
mFullAccess = false;
status = false;
}
}
}
/* 4 - Let's block everything since neither ARA, ARF or fullaccess can be used */
if (!mUseArf && !mUseAra && !mFullAccess) {
mInitialChannelAccess.setApduAccess(ChannelAccess.ACCESS.DENIED);
mInitialChannelAccess.setNFCEventAccess(ChannelAccess.ACCESS.DENIED);
mInitialChannelAccess.setAccess(ChannelAccess.ACCESS.DENIED, denyMsg);
Log.i(mTag, "Deny any access to:" + mTerminal.getName());
}
mRulesRead = status;
}
/**
* Returns the result of the previous attempt to select ARA and/or ARF.
*
* @return true if no rule was found in the previous attempt.
*/
public boolean isNoRuleFound() {
return mNoRuleFound;
}
/** Check if the Channel has permission for the given APDU */
public synchronized void checkCommand(Channel channel, byte[] command) {
ChannelAccess ca = channel.getChannelAccess();
if (ca == null) {
throw new AccessControlException(mTag + "Channel access not set");
}
String reason = ca.getReason();
if (reason.length() == 0) {
reason = "Unspecified";
}
if (DEBUG) {
Log.i(mTag, "checkCommand() : Access = " + ca.getAccess() + " APDU Access = "
+ ca.getApduAccess() + " Reason = " + reason);
}
if (ca.getAccess() != ACCESS.ALLOWED) {
throw new AccessControlException(mTag + reason);
}
if (ca.isUseApduFilter()) {
ApduFilter[] accessConditions = ca.getApduFilter();
if (accessConditions == null || accessConditions.length == 0) {
throw new AccessControlException(mTag + "Access Rule not available:"
+ reason);
}
for (ApduFilter ac : accessConditions) {
if (CommandApdu.compareHeaders(command, ac.getMask(), ac.getApdu())) {
return;
}
}
throw new AccessControlException(mTag + "Access Rule does not match: "
+ reason);
}
if (ca.getApduAccess() == ChannelAccess.ACCESS.ALLOWED) {
return;
} else {
throw new AccessControlException(mTag + "APDU access NOT allowed");
}
}
/** Sets up the Channel Access for the given Package */
public ChannelAccess setUpChannelAccess(byte[] aid, String packageName, boolean checkRefreshTag)
throws IOException, MissingResourceException {
if (packageName.equals("com.finshell.wallet") || packageName.equals("cn.oneplus.wallet")) {
ChannelAccess opBackdoor = new ChannelAccess();
opBackdoor.setAccess(ChannelAccess.ACCESS.ALLOWED, "");
opBackdoor.setApduAccess(ChannelAccess.ACCESS.ALLOWED);
opBackdoor.setNFCEventAccess(ChannelAccess.ACCESS.ALLOWED);
opBackdoor.setPackageName(packageName);
return opBackdoor.clone();
}
ChannelAccess channelAccess = null;
// check result of channel access during initialization procedure
if (mInitialChannelAccess.getAccess() == ChannelAccess.ACCESS.DENIED) {
throw new AccessControlException(
mTag + "access denied: " + mInitialChannelAccess.getReason());
}
// this is the new GP Access Control Enforcer implementation
if (mUseAra || mUseArf) {
channelAccess = internal_setUpChannelAccess(aid, packageName,
checkRefreshTag);
}
if (channelAccess == null || (channelAccess.getApduAccess() != ChannelAccess.ACCESS.ALLOWED
&& !channelAccess.isUseApduFilter())) {
if (mFullAccess) {
// if full access is set then we reuse the initial channel access,
// since we got so far it allows everything with a descriptive reason.
channelAccess = mInitialChannelAccess;
} else {
throw new AccessControlException(mTag + "no APDU access allowed!");
}
}
channelAccess.setPackageName(packageName);
return channelAccess.clone();
}
private synchronized ChannelAccess internal_setUpChannelAccess(byte[] aid,
String packageName, boolean checkRefreshTag) throws IOException,
MissingResourceException {
if (packageName == null || packageName.isEmpty()) {
throw new AccessControlException("package names must be specified");
}
try {
// estimate SHA-1 and SHA-256 hash values of the device application's certificate.
List<byte[]> appCertHashes = getAppCertHashes(packageName);
// APP certificates must be available => otherwise Exception
if (appCertHashes == null || appCertHashes.size() == 0) {
throw new AccessControlException(
"Application certificates are invalid or do not exist.");
}
if (checkRefreshTag) {
updateAccessRuleIfNeed();
}
return getAccessRule(aid, appCertHashes);
} catch (IOException | MissingResourceException e) {
throw e;
} catch (Throwable exp) {
throw new AccessControlException(exp.getMessage());
}
}
/** Fetches the Access Rules for the given application and AID pair */
public ChannelAccess getAccessRule(
byte[] aid, List<byte []> appCertHashes)
throws AccessControlException {
if (DEBUG) {
for (byte[] appCertHash : appCertHashes) {
Log.i(mTag, "getAccessRule() appCert = "
+ ByteArrayConverter.byteArrayToHexString(appCertHash));
}
}
ChannelAccess channelAccess = null;
// if read all is true get rule from cache.
if (mRulesRead) {
// get rules from internal storage
channelAccess = mAccessRuleCache.findAccessRule(aid, appCertHashes);
}
// if no rule was found return an empty access rule
// with all access denied.
if (channelAccess == null) {
channelAccess = new ChannelAccess();
channelAccess.setAccess(ChannelAccess.ACCESS.DENIED, "no access rule found!");
channelAccess.setApduAccess(ChannelAccess.ACCESS.DENIED);
channelAccess.setNFCEventAccess(ChannelAccess.ACCESS.DENIED);
}
return channelAccess;
}
/**
* Returns hashes of certificate chain for one package.
*/
private List<byte[]> getAppCertHashes(String packageName)
throws NoSuchAlgorithmException, AccessControlException {
if (packageName == null || packageName.length() == 0) {
throw new AccessControlException("Package Name not defined");
}
PackageInfo foundPkgInfo;
try {
foundPkgInfo = mPackageManager.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
} catch (NameNotFoundException ne) {
throw new AccessControlException("Package does not exist");
}
if (foundPkgInfo == null) {
throw new AccessControlException("Package does not exist");
}
MessageDigest md = MessageDigest.getInstance("SHA");
MessageDigest md256 = MessageDigest.getInstance("SHA-256");
if (md == null || md256 == null) {
throw new AccessControlException("Hash can not be computed");
}
List<byte[]> appCertHashes = new ArrayList<byte[]>();
for (Signature signature : foundPkgInfo.signatures) {
appCertHashes.add(md.digest(signature.toByteArray()));
appCertHashes.add(md256.digest(signature.toByteArray()));
}
return appCertHashes;
}
/** Returns true if the given application is allowed to recieve NFC Events */
public synchronized boolean[] isNfcEventAllowed(byte[] aid,
String[] packageNames) {
if (mUseAra || mUseArf) {
return internal_isNfcEventAllowed(aid, packageNames);
} else {
// if ARA and ARF is not available and
// - terminal DOES NOT belong to a UICC -> mFullAccess is true
// - terminal belongs to a UICC -> mFullAccess is false
boolean[] ret = new boolean[packageNames.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = mFullAccess;
}
return ret;
}
}
private synchronized boolean[] internal_isNfcEventAllowed(byte[] aid,
String[] packageNames) {
int i = 0;
boolean[] nfcEventFlags = new boolean[packageNames.length];
for (String packageName : packageNames) {
// estimate hash value of the device application's certificate.
try {
List<byte[]> appCertHashes = getAppCertHashes(packageName);
// APP certificates must be available => otherwise Exception
if (appCertHashes == null || appCertHashes.size() == 0) {
nfcEventFlags[i] = false;
} else {
ChannelAccess channelAccess = getAccessRule(aid, appCertHashes);
nfcEventFlags[i] =
(channelAccess.getNFCEventAccess() == ChannelAccess.ACCESS.ALLOWED);
}
} catch (Exception e) {
Log.w(mTag, " Access Rules for NFC: " + e.getLocalizedMessage());
nfcEventFlags[i] = false;
}
i++;
}
return nfcEventFlags;
}
private void updateAccessRuleIfNeed() throws IOException {
if (mUseAra && mAraController != null) {
try {
mAraController.initialize();
mUseArf = false;
mFullAccess = false;
} catch (IOException | MissingResourceException e) {
// There was a communication error between the terminal and the secure element
// or failure in retrieving rules due to the lack of a new logical channel.
// These errors must be distinguished from other ones.
throw e;
} catch (Exception e) {
throw new AccessControlException("No ARA applet found in " + mTerminal.getName());
}
} else if (mUseArf && mArfController != null) {
try {
mArfController.initialize();
} catch (IOException | MissingResourceException e) {
// There was a communication error between the terminal and the secure element
// or failure in retrieving rules due to the lack of a new logical channel.
// These errors must be distinguished from other ones.
throw e;
} catch (Exception e) {
throw new AccessControlException("No ARF found in " + mTerminal.getName());
}
}
}
/** Returns true if the given package has Carrier Privileges */
public synchronized boolean checkCarrierPrivilege(PackageInfo pInfo, boolean checkRefreshTag) {
if (!mUseAra && !mUseArf) {
return false;
}
if (checkRefreshTag) {
try {
updateAccessRuleIfNeed();
} catch (IOException | MissingResourceException e) {
throw new AccessControlException("Access-Control not found in "
+ mTerminal.getName());
}
}
if (!mRulesRead) {
return false;
}
try {
List<byte[]> appCertHashes = getAppCertHashes(pInfo.packageName);
if (appCertHashes == null || appCertHashes.size() == 0) {
return false;
}
return mAccessRuleCache.checkCarrierPrivilege(pInfo.packageName, appCertHashes);
} catch (Exception e) {
Log.w(mTag, " checkCarrierPrivilege: " + e.getLocalizedMessage());
}
return false;
}
/** Debug information to be used by dumpsys */
public void dump(PrintWriter writer) {
writer.println(mTag + ":");
writer.println("mUseArf: " + mUseArf);
writer.println("mUseAra: " + mUseAra);
if (mUseAra && mAraController != null) {
if (getDefaultAccessControlAid() == null) {
writer.println("AraInUse: default applet");
} else {
writer.println("AraInUse: " + ByteArrayConverter.byteArrayToHexString(
getDefaultAccessControlAid()));
}
}
writer.println("mInitialChannelAccess:");
writer.println(mInitialChannelAccess.toString());
writer.println();
/* Dump the access rule cache */
if (mAccessRuleCache != null) mAccessRuleCache.dump(writer);
}
private void readSecurityProfile() {
if (!Build.IS_DEBUGGABLE) {
mUseArf = true;
mUseAra = true;
mFullAccess = false; // Per default we don't grant full access.
} else {
String level = SystemProperties.get("service.seek", "useara usearf");
level = SystemProperties.get("persist.service.seek", level);
if (level.contains("usearf")) {
mUseArf = true;
} else {
mUseArf = false;
}
if (level.contains("useara")) {
mUseAra = true;
} else {
mUseAra = false;
}
if (level.contains("fullaccess")) {
mFullAccess = true;
} else {
mFullAccess = false;
}
}
if (!mTerminal.getName().startsWith(SecureElementService.UICC_TERMINAL)) {
// ARF is supported only on UICC.
mUseArf = false;
}
Log.i(
mTag,
"Allowed ACE mode: ara=" + mUseAra + " arf=" + mUseArf + " fullaccess="
+ mFullAccess);
}
}
|