1 /* 2 * Copyright (C) 2012 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 17 package com.android.server.pm; 18 19 import android.compat.annotation.ChangeId; 20 import android.compat.annotation.EnabledAfter; 21 import android.content.pm.ApplicationInfo; 22 import android.content.pm.PackageParser.SigningDetails; 23 import android.content.pm.Signature; 24 import android.os.Environment; 25 import android.util.Slog; 26 import android.util.Xml; 27 28 import com.android.server.compat.PlatformCompat; 29 import com.android.server.pm.parsing.pkg.AndroidPackage; 30 31 import libcore.io.IoUtils; 32 33 import org.xmlpull.v1.XmlPullParser; 34 import org.xmlpull.v1.XmlPullParserException; 35 36 import java.io.File; 37 import java.io.FileReader; 38 import java.io.IOException; 39 import java.util.ArrayList; 40 import java.util.Collections; 41 import java.util.Comparator; 42 import java.util.HashMap; 43 import java.util.HashSet; 44 import java.util.List; 45 import java.util.Map; 46 import java.util.Set; 47 48 /** 49 * Centralized access to SELinux MMAC (middleware MAC) implementation. This 50 * class is responsible for loading the appropriate mac_permissions.xml file 51 * as well as providing an interface for assigning seinfo values to apks. 52 * 53 * {@hide} 54 */ 55 public final class SELinuxMMAC { 56 57 static final String TAG = "SELinuxMMAC"; 58 59 private static final boolean DEBUG_POLICY = false; 60 private static final boolean DEBUG_POLICY_INSTALL = DEBUG_POLICY || false; 61 private static final boolean DEBUG_POLICY_ORDER = DEBUG_POLICY || false; 62 63 // All policy stanzas read from mac_permissions.xml. This is also the lock 64 // to synchronize access during policy load and access attempts. 65 private static List<Policy> sPolicies = new ArrayList<>(); 66 /** Whether or not the policy files have been read */ 67 private static boolean sPolicyRead; 68 69 /** Required MAC permissions files */ 70 private static List<File> sMacPermissions = new ArrayList<>(); 71 72 private static final String DEFAULT_SEINFO = "default"; 73 74 // Append privapp to existing seinfo label 75 private static final String PRIVILEGED_APP_STR = ":privapp"; 76 77 // Append targetSdkVersion=n to existing seinfo label where n is the app's targetSdkVersion 78 private static final String TARGETSDKVERSION_STR = ":targetSdkVersion="; 79 80 /** 81 * Allows opt-in to the latest targetSdkVersion enforced changes without changing target SDK. 82 * Turning this change off for an app targeting the latest SDK is a no-op. 83 * 84 * <p>Has no effect for apps using shared user id. 85 * 86 * TODO(b/143539591): Update description with relevant SELINUX changes this opts in to. 87 */ 88 @EnabledAfter(targetSdkVersion = android.os.Build.VERSION_CODES.R) 89 @ChangeId 90 static final long SELINUX_LATEST_CHANGES = 143539591L; 91 92 /** 93 * This change gates apps access to untrusted_app_R-targetSDK SELinux domain. Allows opt-in 94 * to R targetSdkVersion enforced changes without changing target SDK. Turning this change 95 * off for an app targeting S is a no-op. 96 * 97 * <p>Has no effect for apps using shared user id. 98 * 99 * TODO(b/143539591): Update description with relevant SELINUX changes this opts in to. 100 */ 101 @EnabledAfter(targetSdkVersion = android.os.Build.VERSION_CODES.Q) 102 @ChangeId 103 static final long SELINUX_R_CHANGES = 168782947L; 104 105 // Only initialize sMacPermissions once. 106 static { 107 // Platform mac permissions. sMacPermissions.add(new File( Environment.getRootDirectory(), "/etc/selinux/plat_mac_permissions.xml"))108 sMacPermissions.add(new File( 109 Environment.getRootDirectory(), "/etc/selinux/plat_mac_permissions.xml")); 110 111 // SystemExt mac permissions (optional). 112 final File systemExtMacPermission = new File( 113 Environment.getSystemExtDirectory(), "/etc/selinux/system_ext_mac_permissions.xml"); 114 if (systemExtMacPermission.exists()) { 115 sMacPermissions.add(systemExtMacPermission); 116 } 117 118 // Product mac permissions (optional). 119 final File productMacPermission = new File( 120 Environment.getProductDirectory(), "/etc/selinux/product_mac_permissions.xml"); 121 if (productMacPermission.exists()) { 122 sMacPermissions.add(productMacPermission); 123 } 124 125 // Vendor mac permissions. 126 // The filename has been renamed from nonplat_mac_permissions to 127 // vendor_mac_permissions. Either of them should exist. 128 final File vendorMacPermission = new File( 129 Environment.getVendorDirectory(), "/etc/selinux/vendor_mac_permissions.xml"); 130 if (vendorMacPermission.exists()) { 131 sMacPermissions.add(vendorMacPermission); 132 } else { 133 // For backward compatibility. sMacPermissions.add(new File(Environment.getVendorDirectory(), "/etc/selinux/nonplat_mac_permissions.xml"))134 sMacPermissions.add(new File(Environment.getVendorDirectory(), 135 "/etc/selinux/nonplat_mac_permissions.xml")); 136 } 137 138 // ODM mac permissions (optional). 139 final File odmMacPermission = new File( 140 Environment.getOdmDirectory(), "/etc/selinux/odm_mac_permissions.xml"); 141 if (odmMacPermission.exists()) { 142 sMacPermissions.add(odmMacPermission); 143 } 144 } 145 146 /** 147 * Load the mac_permissions.xml file containing all seinfo assignments used to 148 * label apps. The loaded mac_permissions.xml files are plat_mac_permissions.xml and 149 * vendor_mac_permissions.xml, on /system and /vendor partitions, respectively. 150 * odm_mac_permissions.xml on /odm partition is optional. For further guidance on 151 * the proper structure of a mac_permissions.xml file consult the source code 152 * located at system/sepolicy/private/mac_permissions.xml. 153 * 154 * @return boolean indicating if policy was correctly loaded. A value of false 155 * typically indicates a structural problem with the xml or incorrectly 156 * constructed policy stanzas. A value of true means that all stanzas 157 * were loaded successfully; no partial loading is possible. 158 */ readInstallPolicy()159 public static boolean readInstallPolicy() { 160 synchronized (sPolicies) { 161 if (sPolicyRead) { 162 return true; 163 } 164 } 165 166 // Temp structure to hold the rules while we parse the xml file 167 List<Policy> policies = new ArrayList<>(); 168 169 FileReader policyFile = null; 170 XmlPullParser parser = Xml.newPullParser(); 171 172 final int count = sMacPermissions.size(); 173 for (int i = 0; i < count; ++i) { 174 final File macPermission = sMacPermissions.get(i); 175 try { 176 policyFile = new FileReader(macPermission); 177 Slog.d(TAG, "Using policy file " + macPermission); 178 179 parser.setInput(policyFile); 180 parser.nextTag(); 181 parser.require(XmlPullParser.START_TAG, null, "policy"); 182 183 while (parser.next() != XmlPullParser.END_TAG) { 184 if (parser.getEventType() != XmlPullParser.START_TAG) { 185 continue; 186 } 187 188 switch (parser.getName()) { 189 case "signer": 190 policies.add(readSignerOrThrow(parser)); 191 break; 192 default: 193 skip(parser); 194 } 195 } 196 } catch (IllegalStateException | IllegalArgumentException | 197 XmlPullParserException ex) { 198 StringBuilder sb = new StringBuilder("Exception @"); 199 sb.append(parser.getPositionDescription()); 200 sb.append(" while parsing "); 201 sb.append(macPermission); 202 sb.append(":"); 203 sb.append(ex); 204 Slog.w(TAG, sb.toString()); 205 return false; 206 } catch (IOException ioe) { 207 Slog.w(TAG, "Exception parsing " + macPermission, ioe); 208 return false; 209 } finally { 210 IoUtils.closeQuietly(policyFile); 211 } 212 } 213 214 // Now sort the policy stanzas 215 PolicyComparator policySort = new PolicyComparator(); 216 Collections.sort(policies, policySort); 217 if (policySort.foundDuplicate()) { 218 Slog.w(TAG, "ERROR! Duplicate entries found parsing mac_permissions.xml files"); 219 return false; 220 } 221 222 synchronized (sPolicies) { 223 sPolicies.clear(); 224 sPolicies.addAll(policies); 225 sPolicyRead = true; 226 227 if (DEBUG_POLICY_ORDER) { 228 for (Policy policy : sPolicies) { 229 Slog.d(TAG, "Policy: " + policy.toString()); 230 } 231 } 232 } 233 234 return true; 235 } 236 237 /** 238 * Loop over a signer tag looking for seinfo, package and cert tags. A {@link Policy} 239 * instance will be created and returned in the process. During the pass all other 240 * tag elements will be skipped. 241 * 242 * @param parser an XmlPullParser object representing a signer element. 243 * @return the constructed {@link Policy} instance 244 * @throws IOException 245 * @throws XmlPullParserException 246 * @throws IllegalArgumentException if any of the validation checks fail while 247 * parsing tag values. 248 * @throws IllegalStateException if any of the invariants fail when constructing 249 * the {@link Policy} instance. 250 */ readSignerOrThrow(XmlPullParser parser)251 private static Policy readSignerOrThrow(XmlPullParser parser) throws IOException, 252 XmlPullParserException { 253 254 parser.require(XmlPullParser.START_TAG, null, "signer"); 255 Policy.PolicyBuilder pb = new Policy.PolicyBuilder(); 256 257 // Check for a cert attached to the signer tag. We allow a signature 258 // to appear as an attribute as well as those attached to cert tags. 259 String cert = parser.getAttributeValue(null, "signature"); 260 if (cert != null) { 261 pb.addSignature(cert); 262 } 263 264 while (parser.next() != XmlPullParser.END_TAG) { 265 if (parser.getEventType() != XmlPullParser.START_TAG) { 266 continue; 267 } 268 269 String tagName = parser.getName(); 270 if ("seinfo".equals(tagName)) { 271 String seinfo = parser.getAttributeValue(null, "value"); 272 pb.setGlobalSeinfoOrThrow(seinfo); 273 readSeinfo(parser); 274 } else if ("package".equals(tagName)) { 275 readPackageOrThrow(parser, pb); 276 } else if ("cert".equals(tagName)) { 277 String sig = parser.getAttributeValue(null, "signature"); 278 pb.addSignature(sig); 279 readCert(parser); 280 } else { 281 skip(parser); 282 } 283 } 284 285 return pb.build(); 286 } 287 288 /** 289 * Loop over a package element looking for seinfo child tags. If found return the 290 * value attribute of the seinfo tag, otherwise return null. All other tags encountered 291 * will be skipped. 292 * 293 * @param parser an XmlPullParser object representing a package element. 294 * @param pb a Policy.PolicyBuilder instance to build 295 * @throws IOException 296 * @throws XmlPullParserException 297 * @throws IllegalArgumentException if any of the validation checks fail while 298 * parsing tag values. 299 * @throws IllegalStateException if there is a duplicate seinfo tag for the current 300 * package tag. 301 */ readPackageOrThrow(XmlPullParser parser, Policy.PolicyBuilder pb)302 private static void readPackageOrThrow(XmlPullParser parser, Policy.PolicyBuilder pb) throws 303 IOException, XmlPullParserException { 304 parser.require(XmlPullParser.START_TAG, null, "package"); 305 String pkgName = parser.getAttributeValue(null, "name"); 306 307 while (parser.next() != XmlPullParser.END_TAG) { 308 if (parser.getEventType() != XmlPullParser.START_TAG) { 309 continue; 310 } 311 312 String tagName = parser.getName(); 313 if ("seinfo".equals(tagName)) { 314 String seinfo = parser.getAttributeValue(null, "value"); 315 pb.addInnerPackageMapOrThrow(pkgName, seinfo); 316 readSeinfo(parser); 317 } else { 318 skip(parser); 319 } 320 } 321 } 322 readCert(XmlPullParser parser)323 private static void readCert(XmlPullParser parser) throws IOException, 324 XmlPullParserException { 325 parser.require(XmlPullParser.START_TAG, null, "cert"); 326 parser.nextTag(); 327 } 328 readSeinfo(XmlPullParser parser)329 private static void readSeinfo(XmlPullParser parser) throws IOException, 330 XmlPullParserException { 331 parser.require(XmlPullParser.START_TAG, null, "seinfo"); 332 parser.nextTag(); 333 } 334 skip(XmlPullParser p)335 private static void skip(XmlPullParser p) throws IOException, XmlPullParserException { 336 if (p.getEventType() != XmlPullParser.START_TAG) { 337 throw new IllegalStateException(); 338 } 339 int depth = 1; 340 while (depth != 0) { 341 switch (p.next()) { 342 case XmlPullParser.END_TAG: 343 depth--; 344 break; 345 case XmlPullParser.START_TAG: 346 depth++; 347 break; 348 } 349 } 350 } 351 getTargetSdkVersionForSeInfo(AndroidPackage pkg, SharedUserSetting sharedUserSetting, PlatformCompat compatibility)352 private static int getTargetSdkVersionForSeInfo(AndroidPackage pkg, 353 SharedUserSetting sharedUserSetting, PlatformCompat compatibility) { 354 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 355 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 356 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 357 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 358 // least restrictive selinux domain. 359 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 360 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 361 // ensures that all packages continue to run in the same selinux domain. 362 if ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) { 363 return sharedUserSetting.seInfoTargetSdkVersion; 364 } 365 final ApplicationInfo appInfo = pkg.toAppInfoWithoutState(); 366 if (compatibility.isChangeEnabledInternal(SELINUX_LATEST_CHANGES, appInfo)) { 367 return android.os.Build.VERSION_CODES.S; 368 } else if (compatibility.isChangeEnabledInternal(SELINUX_R_CHANGES, appInfo)) { 369 return Math.max(android.os.Build.VERSION_CODES.R, pkg.getTargetSdkVersion()); 370 } 371 372 return pkg.getTargetSdkVersion(); 373 } 374 375 /** 376 * Selects a security label to a package based on input parameters and the seinfo tag taken 377 * from a matched policy. All signature based policy stanzas are consulted and, if no match 378 * is found, the default seinfo label of 'default' is used. The security label is attached to 379 * the ApplicationInfo instance of the package. 380 * 381 * @param pkg object representing the package to be labeled. 382 * @param sharedUserSetting if the app shares a sharedUserId, then this has the shared setting. 383 * @param compatibility the PlatformCompat service to ask about state of compat changes. 384 * @return String representing the resulting seinfo. 385 */ getSeInfo(AndroidPackage pkg, SharedUserSetting sharedUserSetting, PlatformCompat compatibility)386 public static String getSeInfo(AndroidPackage pkg, SharedUserSetting sharedUserSetting, 387 PlatformCompat compatibility) { 388 final int targetSdkVersion = getTargetSdkVersionForSeInfo(pkg, sharedUserSetting, 389 compatibility); 390 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 391 // They currently can be if the sharedUser apps are signed with the platform key. 392 final boolean isPrivileged = (sharedUserSetting != null) 393 ? sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 394 return getSeInfo(pkg, isPrivileged, targetSdkVersion); 395 } 396 397 /** 398 * Selects a security label to a package based on input parameters and the seinfo tag taken 399 * from a matched policy. All signature based policy stanzas are consulted and, if no match 400 * is found, the default seinfo label of 'default' is used. The security label is attached to 401 * the ApplicationInfo instance of the package. 402 * 403 * @param pkg object representing the package to be labeled. 404 * @param isPrivileged boolean. 405 * @param targetSdkVersion int. If this pkg runs as a sharedUser, targetSdkVersion is the 406 * greater of: lowest targetSdk for all pkgs in the sharedUser, or 407 * MINIMUM_TARGETSDKVERSION. 408 * @return String representing the resulting seinfo. 409 */ getSeInfo(AndroidPackage pkg, boolean isPrivileged, int targetSdkVersion)410 public static String getSeInfo(AndroidPackage pkg, boolean isPrivileged, 411 int targetSdkVersion) { 412 String seInfo = null; 413 synchronized (sPolicies) { 414 if (!sPolicyRead) { 415 if (DEBUG_POLICY) { 416 Slog.d(TAG, "Policy not read"); 417 } 418 } else { 419 for (Policy policy : sPolicies) { 420 seInfo = policy.getMatchedSeInfo(pkg); 421 if (seInfo != null) { 422 break; 423 } 424 } 425 } 426 } 427 428 if (seInfo == null) { 429 seInfo = DEFAULT_SEINFO; 430 } 431 432 if (isPrivileged) { 433 seInfo += PRIVILEGED_APP_STR; 434 } 435 436 seInfo += TARGETSDKVERSION_STR + targetSdkVersion; 437 438 if (DEBUG_POLICY_INSTALL) { 439 Slog.i(TAG, "package (" + pkg.getPackageName() + ") labeled with " 440 + "seinfo=" + seInfo); 441 } 442 return seInfo; 443 } 444 } 445 446 /** 447 * Holds valid policy representations of individual stanzas from a mac_permissions.xml 448 * file. Each instance can further be used to assign seinfo values to apks using the 449 * {@link Policy#getMatchedSeInfo(AndroidPackage)} method. To create an instance of this use the 450 * {@link PolicyBuilder} pattern class, where each instance is validated against a set 451 * of invariants before being built and returned. Each instance can be guaranteed to 452 * hold one valid policy stanza as outlined in the system/sepolicy/mac_permissions.xml 453 * file. 454 * <p> 455 * The following is an example of how to use {@link Policy.PolicyBuilder} to create a 456 * signer based Policy instance with only inner package name refinements. 457 * </p> 458 * <pre> 459 * {@code 460 * Policy policy = new Policy.PolicyBuilder() 461 * .addSignature("308204a8...") 462 * .addSignature("483538c8...") 463 * .addInnerPackageMapOrThrow("com.foo.", "bar") 464 * .addInnerPackageMapOrThrow("com.foo.other", "bar") 465 * .build(); 466 * } 467 * </pre> 468 * <p> 469 * The following is an example of how to use {@link Policy.PolicyBuilder} to create a 470 * signer based Policy instance with only a global seinfo tag. 471 * </p> 472 * <pre> 473 * {@code 474 * Policy policy = new Policy.PolicyBuilder() 475 * .addSignature("308204a8...") 476 * .addSignature("483538c8...") 477 * .setGlobalSeinfoOrThrow("paltform") 478 * .build(); 479 * } 480 * </pre> 481 */ 482 final class Policy { 483 484 private final String mSeinfo; 485 private final Set<Signature> mCerts; 486 private final Map<String, String> mPkgMap; 487 488 // Use the PolicyBuilder pattern to instantiate Policy(PolicyBuilder builder)489 private Policy(PolicyBuilder builder) { 490 mSeinfo = builder.mSeinfo; 491 mCerts = Collections.unmodifiableSet(builder.mCerts); 492 mPkgMap = Collections.unmodifiableMap(builder.mPkgMap); 493 } 494 495 /** 496 * Return all the certs stored with this policy stanza. 497 * 498 * @return A set of Signature objects representing all the certs stored 499 * with the policy. 500 */ getSignatures()501 public Set<Signature> getSignatures() { 502 return mCerts; 503 } 504 505 /** 506 * Return whether this policy object contains package name mapping refinements. 507 * 508 * @return A boolean indicating if this object has inner package name mappings. 509 */ hasInnerPackages()510 public boolean hasInnerPackages() { 511 return !mPkgMap.isEmpty(); 512 } 513 514 /** 515 * Return the mapping of all package name refinements. 516 * 517 * @return A Map object whose keys are the package names and whose values are 518 * the seinfo assignments. 519 */ getInnerPackages()520 public Map<String, String> getInnerPackages() { 521 return mPkgMap; 522 } 523 524 /** 525 * Return whether the policy object has a global seinfo tag attached. 526 * 527 * @return A boolean indicating if this stanza has a global seinfo tag. 528 */ hasGlobalSeinfo()529 public boolean hasGlobalSeinfo() { 530 return mSeinfo != null; 531 } 532 533 @Override toString()534 public String toString() { 535 StringBuilder sb = new StringBuilder(); 536 for (Signature cert : mCerts) { 537 sb.append("cert=" + cert.toCharsString().substring(0, 11) + "... "); 538 } 539 540 if (mSeinfo != null) { 541 sb.append("seinfo=" + mSeinfo); 542 } 543 544 for (String name : mPkgMap.keySet()) { 545 sb.append(" " + name + "=" + mPkgMap.get(name)); 546 } 547 548 return sb.toString(); 549 } 550 551 /** 552 * <p> 553 * Determine the seinfo value to assign to an apk. The appropriate seinfo value 554 * is determined using the following steps: 555 * </p> 556 * <ul> 557 * <li> All certs used to sign the apk and all certs stored with this policy 558 * instance are tested for set equality. If this fails then null is returned. 559 * </li> 560 * <li> If all certs match then an appropriate inner package stanza is 561 * searched based on package name alone. If matched, the stored seinfo 562 * value for that mapping is returned. 563 * </li> 564 * <li> If all certs matched and no inner package stanza matches then return 565 * the global seinfo value. The returned value can be null in this case. 566 * </li> 567 * </ul> 568 * <p> 569 * In all cases, a return value of null should be interpreted as the apk failing 570 * to match this Policy instance; i.e. failing this policy stanza. 571 * </p> 572 * @param pkg the apk to check given as a PackageParser.Package object 573 * @return A string representing the seinfo matched during policy lookup. 574 * A value of null can also be returned if no match occured. 575 */ getMatchedSeInfo(AndroidPackage pkg)576 public String getMatchedSeInfo(AndroidPackage pkg) { 577 // Check for exact signature matches across all certs. 578 Signature[] certs = mCerts.toArray(new Signature[0]); 579 if (pkg.getSigningDetails() != SigningDetails.UNKNOWN 580 && !Signature.areExactMatch(certs, pkg.getSigningDetails().signatures)) { 581 582 // certs aren't exact match, but the package may have rotated from the known system cert 583 if (certs.length > 1 || !pkg.getSigningDetails().hasCertificate(certs[0])) { 584 return null; 585 } 586 } 587 588 // Check for inner package name matches given that the 589 // signature checks already passed. 590 String seinfoValue = mPkgMap.get(pkg.getPackageName()); 591 if (seinfoValue != null) { 592 return seinfoValue; 593 } 594 595 // Return the global seinfo value. 596 return mSeinfo; 597 } 598 599 /** 600 * A nested builder class to create {@link Policy} instances. A {@link Policy} 601 * class instance represents one valid policy stanza found in a mac_permissions.xml 602 * file. A valid policy stanza is defined to be a signer stanza which obeys the rules 603 * outlined in system/sepolicy/mac_permissions.xml. The {@link #build} method 604 * ensures a set of invariants are upheld enforcing the correct stanza structure 605 * before returning a valid Policy object. 606 */ 607 public static final class PolicyBuilder { 608 609 private String mSeinfo; 610 private final Set<Signature> mCerts; 611 private final Map<String, String> mPkgMap; 612 PolicyBuilder()613 public PolicyBuilder() { 614 mCerts = new HashSet<Signature>(2); 615 mPkgMap = new HashMap<String, String>(2); 616 } 617 618 /** 619 * Adds a signature to the set of certs used for validation checks. The purpose 620 * being that all contained certs will need to be matched against all certs 621 * contained with an apk. 622 * 623 * @param cert the signature to add given as a String. 624 * @return The reference to this PolicyBuilder. 625 * @throws IllegalArgumentException if the cert value fails validation; 626 * null or is an invalid hex-encoded ASCII string. 627 */ addSignature(String cert)628 public PolicyBuilder addSignature(String cert) { 629 if (cert == null) { 630 String err = "Invalid signature value " + cert; 631 throw new IllegalArgumentException(err); 632 } 633 634 mCerts.add(new Signature(cert)); 635 return this; 636 } 637 638 /** 639 * Set the global seinfo tag for this policy stanza. The global seinfo tag 640 * when attached to a signer tag represents the assignment when there isn't a 641 * further inner package refinement in policy. 642 * 643 * @param seinfo the seinfo value given as a String. 644 * @return The reference to this PolicyBuilder. 645 * @throws IllegalArgumentException if the seinfo value fails validation; 646 * null, zero length or contains non-valid characters [^a-zA-Z_\._0-9]. 647 * @throws IllegalStateException if an seinfo value has already been found 648 */ setGlobalSeinfoOrThrow(String seinfo)649 public PolicyBuilder setGlobalSeinfoOrThrow(String seinfo) { 650 if (!validateValue(seinfo)) { 651 String err = "Invalid seinfo value " + seinfo; 652 throw new IllegalArgumentException(err); 653 } 654 655 if (mSeinfo != null && !mSeinfo.equals(seinfo)) { 656 String err = "Duplicate seinfo tag found"; 657 throw new IllegalStateException(err); 658 } 659 660 mSeinfo = seinfo; 661 return this; 662 } 663 664 /** 665 * Create a package name to seinfo value mapping. Each mapping represents 666 * the seinfo value that will be assigned to the described package name. 667 * These localized mappings allow the global seinfo to be overriden. 668 * 669 * @param pkgName the android package name given to the app 670 * @param seinfo the seinfo value that will be assigned to the passed pkgName 671 * @return The reference to this PolicyBuilder. 672 * @throws IllegalArgumentException if the seinfo value fails validation; 673 * null, zero length or contains non-valid characters [^a-zA-Z_\.0-9]. 674 * Or, if the package name isn't a valid android package name. 675 * @throws IllegalStateException if trying to reset a package mapping with a 676 * different seinfo value. 677 */ addInnerPackageMapOrThrow(String pkgName, String seinfo)678 public PolicyBuilder addInnerPackageMapOrThrow(String pkgName, String seinfo) { 679 if (!validateValue(pkgName)) { 680 String err = "Invalid package name " + pkgName; 681 throw new IllegalArgumentException(err); 682 } 683 if (!validateValue(seinfo)) { 684 String err = "Invalid seinfo value " + seinfo; 685 throw new IllegalArgumentException(err); 686 } 687 688 String pkgValue = mPkgMap.get(pkgName); 689 if (pkgValue != null && !pkgValue.equals(seinfo)) { 690 String err = "Conflicting seinfo value found"; 691 throw new IllegalStateException(err); 692 } 693 694 mPkgMap.put(pkgName, seinfo); 695 return this; 696 } 697 698 /** 699 * General validation routine for the attribute strings of an element. Checks 700 * if the string is non-null, positive length and only contains [a-zA-Z_\.0-9]. 701 * 702 * @param name the string to validate. 703 * @return boolean indicating if the string was valid. 704 */ validateValue(String name)705 private boolean validateValue(String name) { 706 if (name == null) 707 return false; 708 709 // Want to match on [0-9a-zA-Z_.] 710 if (!name.matches("\\A[\\.\\w]+\\z")) { 711 return false; 712 } 713 714 return true; 715 } 716 717 /** 718 * <p> 719 * Create a {@link Policy} instance based on the current configuration. This 720 * method checks for certain policy invariants used to enforce certain guarantees 721 * about the expected structure of a policy stanza. 722 * Those invariants are: 723 * </p> 724 * <ul> 725 * <li> at least one cert must be found </li> 726 * <li> either a global seinfo value is present OR at least one 727 * inner package mapping must be present BUT not both. </li> 728 * </ul> 729 * @return an instance of {@link Policy} with the options set from this builder 730 * @throws IllegalStateException if an invariant is violated. 731 */ build()732 public Policy build() { 733 Policy p = new Policy(this); 734 735 if (p.mCerts.isEmpty()) { 736 String err = "Missing certs with signer tag. Expecting at least one."; 737 throw new IllegalStateException(err); 738 } 739 if (!(p.mSeinfo == null ^ p.mPkgMap.isEmpty())) { 740 String err = "Only seinfo tag XOR package tags are allowed within " + 741 "a signer stanza."; 742 throw new IllegalStateException(err); 743 } 744 745 return p; 746 } 747 } 748 } 749 750 /** 751 * Comparision imposing an ordering on Policy objects. It is understood that Policy 752 * objects can only take one of three forms and ordered according to the following 753 * set of rules most specific to least. 754 * <ul> 755 * <li> signer stanzas with inner package mappings </li> 756 * <li> signer stanzas with global seinfo tags </li> 757 * </ul> 758 * This comparison also checks for duplicate entries on the input selectors. Any 759 * found duplicates will be flagged and can be checked with {@link #foundDuplicate}. 760 */ 761 762 final class PolicyComparator implements Comparator<Policy> { 763 764 private boolean duplicateFound = false; 765 foundDuplicate()766 public boolean foundDuplicate() { 767 return duplicateFound; 768 } 769 770 @Override compare(Policy p1, Policy p2)771 public int compare(Policy p1, Policy p2) { 772 773 // Give precedence to stanzas with inner package mappings 774 if (p1.hasInnerPackages() != p2.hasInnerPackages()) { 775 return p1.hasInnerPackages() ? -1 : 1; 776 } 777 778 // Check for duplicate entries 779 if (p1.getSignatures().equals(p2.getSignatures())) { 780 // Checks if signer w/o inner package names 781 if (p1.hasGlobalSeinfo()) { 782 duplicateFound = true; 783 Slog.e(SELinuxMMAC.TAG, "Duplicate policy entry: " + p1.toString()); 784 } 785 786 // Look for common inner package name mappings 787 final Map<String, String> p1Packages = p1.getInnerPackages(); 788 final Map<String, String> p2Packages = p2.getInnerPackages(); 789 if (!Collections.disjoint(p1Packages.keySet(), p2Packages.keySet())) { 790 duplicateFound = true; 791 Slog.e(SELinuxMMAC.TAG, "Duplicate policy entry: " + p1.toString()); 792 } 793 } 794 795 return 0; 796 } 797 } 798