SELinuxMMAC.java revision 60747d28230c5a78e30fc8836946a8a8806ab738
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
17package com.android.server.pm;
18
19import android.content.pm.PackageParser;
20import android.content.pm.Signature;
21import android.content.pm.PackageParser.SigningDetails;
22import android.os.Environment;
23import android.util.Slog;
24import android.util.Xml;
25
26import libcore.io.IoUtils;
27
28import org.xmlpull.v1.XmlPullParser;
29import org.xmlpull.v1.XmlPullParserException;
30
31import java.io.File;
32import java.io.FileReader;
33import java.io.IOException;
34import java.util.ArrayList;
35import java.util.Collections;
36import java.util.Comparator;
37import java.util.HashMap;
38import java.util.HashSet;
39import java.util.List;
40import java.util.Map;
41import java.util.Set;
42
43/**
44 * Centralized access to SELinux MMAC (middleware MAC) implementation. This
45 * class is responsible for loading the appropriate mac_permissions.xml file
46 * as well as providing an interface for assigning seinfo values to apks.
47 *
48 * {@hide}
49 */
50public final class SELinuxMMAC {
51
52    static final String TAG = "SELinuxMMAC";
53
54    private static final boolean DEBUG_POLICY = false;
55    private static final boolean DEBUG_POLICY_INSTALL = DEBUG_POLICY || false;
56    private static final boolean DEBUG_POLICY_ORDER = DEBUG_POLICY || false;
57
58    // All policy stanzas read from mac_permissions.xml. This is also the lock
59    // to synchronize access during policy load and access attempts.
60    private static List<Policy> sPolicies = new ArrayList<>();
61    /** Whether or not the policy files have been read */
62    private static boolean sPolicyRead;
63
64    /** Path to MAC permissions on system image */
65    private static final File[] MAC_PERMISSIONS =
66    { new File(Environment.getRootDirectory(), "/etc/selinux/plat_mac_permissions.xml"),
67      new File(Environment.getVendorDirectory(), "/etc/selinux/nonplat_mac_permissions.xml") };
68
69    // Append privapp to existing seinfo label
70    private static final String PRIVILEGED_APP_STR = ":privapp";
71
72    // Append v2 to existing seinfo label
73    private static final String SANDBOX_V2_STR = ":v2";
74
75    // Append targetSdkVersion=n to existing seinfo label where n is the app's targetSdkVersion
76    private static final String TARGETSDKVERSION_STR = ":targetSdkVersion=";
77
78    /**
79     * Load the mac_permissions.xml file containing all seinfo assignments used to
80     * label apps. The loaded mac_permissions.xml file is determined by the
81     * MAC_PERMISSIONS class variable which is set at class load time which itself
82     * is based on the USE_OVERRIDE_POLICY class variable. For further guidance on
83     * the proper structure of a mac_permissions.xml file consult the source code
84     * located at system/sepolicy/mac_permissions.xml.
85     *
86     * @return boolean indicating if policy was correctly loaded. A value of false
87     *         typically indicates a structural problem with the xml or incorrectly
88     *         constructed policy stanzas. A value of true means that all stanzas
89     *         were loaded successfully; no partial loading is possible.
90     */
91    public static boolean readInstallPolicy() {
92        synchronized (sPolicies) {
93            if (sPolicyRead) {
94                return true;
95            }
96        }
97
98        // Temp structure to hold the rules while we parse the xml file
99        List<Policy> policies = new ArrayList<>();
100
101        FileReader policyFile = null;
102        XmlPullParser parser = Xml.newPullParser();
103        for (int i = 0; i < MAC_PERMISSIONS.length; i++) {
104            try {
105                policyFile = new FileReader(MAC_PERMISSIONS[i]);
106                Slog.d(TAG, "Using policy file " + MAC_PERMISSIONS[i]);
107
108                parser.setInput(policyFile);
109                parser.nextTag();
110                parser.require(XmlPullParser.START_TAG, null, "policy");
111
112                while (parser.next() != XmlPullParser.END_TAG) {
113                    if (parser.getEventType() != XmlPullParser.START_TAG) {
114                        continue;
115                    }
116
117                    switch (parser.getName()) {
118                        case "signer":
119                            policies.add(readSignerOrThrow(parser));
120                            break;
121                        default:
122                            skip(parser);
123                    }
124                }
125            } catch (IllegalStateException | IllegalArgumentException |
126                     XmlPullParserException ex) {
127                StringBuilder sb = new StringBuilder("Exception @");
128                sb.append(parser.getPositionDescription());
129                sb.append(" while parsing ");
130                sb.append(MAC_PERMISSIONS[i]);
131                sb.append(":");
132                sb.append(ex);
133                Slog.w(TAG, sb.toString());
134                return false;
135            } catch (IOException ioe) {
136                Slog.w(TAG, "Exception parsing " + MAC_PERMISSIONS[i], ioe);
137                return false;
138            } finally {
139                IoUtils.closeQuietly(policyFile);
140            }
141        }
142
143        // Now sort the policy stanzas
144        PolicyComparator policySort = new PolicyComparator();
145        Collections.sort(policies, policySort);
146        if (policySort.foundDuplicate()) {
147            Slog.w(TAG, "ERROR! Duplicate entries found parsing mac_permissions.xml files");
148            return false;
149        }
150
151        synchronized (sPolicies) {
152            sPolicies.clear();
153            sPolicies.addAll(policies);
154            sPolicyRead = true;
155
156            if (DEBUG_POLICY_ORDER) {
157                for (Policy policy : sPolicies) {
158                    Slog.d(TAG, "Policy: " + policy.toString());
159                }
160            }
161        }
162
163        return true;
164    }
165
166    /**
167     * Loop over a signer tag looking for seinfo, package and cert tags. A {@link Policy}
168     * instance will be created and returned in the process. During the pass all other
169     * tag elements will be skipped.
170     *
171     * @param parser an XmlPullParser object representing a signer element.
172     * @return the constructed {@link Policy} instance
173     * @throws IOException
174     * @throws XmlPullParserException
175     * @throws IllegalArgumentException if any of the validation checks fail while
176     *         parsing tag values.
177     * @throws IllegalStateException if any of the invariants fail when constructing
178     *         the {@link Policy} instance.
179     */
180    private static Policy readSignerOrThrow(XmlPullParser parser) throws IOException,
181            XmlPullParserException {
182
183        parser.require(XmlPullParser.START_TAG, null, "signer");
184        Policy.PolicyBuilder pb = new Policy.PolicyBuilder();
185
186        // Check for a cert attached to the signer tag. We allow a signature
187        // to appear as an attribute as well as those attached to cert tags.
188        String cert = parser.getAttributeValue(null, "signature");
189        if (cert != null) {
190            pb.addSignature(cert);
191        }
192
193        while (parser.next() != XmlPullParser.END_TAG) {
194            if (parser.getEventType() != XmlPullParser.START_TAG) {
195                continue;
196            }
197
198            String tagName = parser.getName();
199            if ("seinfo".equals(tagName)) {
200                String seinfo = parser.getAttributeValue(null, "value");
201                pb.setGlobalSeinfoOrThrow(seinfo);
202                readSeinfo(parser);
203            } else if ("package".equals(tagName)) {
204                readPackageOrThrow(parser, pb);
205            } else if ("cert".equals(tagName)) {
206                String sig = parser.getAttributeValue(null, "signature");
207                pb.addSignature(sig);
208                readCert(parser);
209            } else {
210                skip(parser);
211            }
212        }
213
214        return pb.build();
215    }
216
217    /**
218     * Loop over a package element looking for seinfo child tags. If found return the
219     * value attribute of the seinfo tag, otherwise return null. All other tags encountered
220     * will be skipped.
221     *
222     * @param parser an XmlPullParser object representing a package element.
223     * @param pb a Policy.PolicyBuilder instance to build
224     * @throws IOException
225     * @throws XmlPullParserException
226     * @throws IllegalArgumentException if any of the validation checks fail while
227     *         parsing tag values.
228     * @throws IllegalStateException if there is a duplicate seinfo tag for the current
229     *         package tag.
230     */
231    private static void readPackageOrThrow(XmlPullParser parser, Policy.PolicyBuilder pb) throws
232            IOException, XmlPullParserException {
233        parser.require(XmlPullParser.START_TAG, null, "package");
234        String pkgName = parser.getAttributeValue(null, "name");
235
236        while (parser.next() != XmlPullParser.END_TAG) {
237            if (parser.getEventType() != XmlPullParser.START_TAG) {
238                continue;
239            }
240
241            String tagName = parser.getName();
242            if ("seinfo".equals(tagName)) {
243                String seinfo = parser.getAttributeValue(null, "value");
244                pb.addInnerPackageMapOrThrow(pkgName, seinfo);
245                readSeinfo(parser);
246            } else {
247                skip(parser);
248            }
249        }
250    }
251
252    private static void readCert(XmlPullParser parser) throws IOException,
253            XmlPullParserException {
254        parser.require(XmlPullParser.START_TAG, null, "cert");
255        parser.nextTag();
256    }
257
258    private static void readSeinfo(XmlPullParser parser) throws IOException,
259            XmlPullParserException {
260        parser.require(XmlPullParser.START_TAG, null, "seinfo");
261        parser.nextTag();
262    }
263
264    private static void skip(XmlPullParser p) throws IOException, XmlPullParserException {
265        if (p.getEventType() != XmlPullParser.START_TAG) {
266            throw new IllegalStateException();
267        }
268        int depth = 1;
269        while (depth != 0) {
270            switch (p.next()) {
271            case XmlPullParser.END_TAG:
272                depth--;
273                break;
274            case XmlPullParser.START_TAG:
275                depth++;
276                break;
277            }
278        }
279    }
280
281    /**
282     * Applies a security label to a package based on an seinfo tag taken from a matched
283     * policy. All signature based policy stanzas are consulted and, if no match is
284     * found, the default seinfo label of 'default' (set in ApplicationInfo object) is
285     * used. The security label is attached to the ApplicationInfo instance of the package
286     * in the event that a matching policy was found.
287     *
288     * @param pkg object representing the package to be labeled.
289     */
290    public static void assignSeInfoValue(PackageParser.Package pkg, boolean isPrivileged,
291            int targetSdkVersion) {
292        synchronized (sPolicies) {
293            if (!sPolicyRead) {
294                if (DEBUG_POLICY) {
295                    Slog.d(TAG, "Policy not read");
296                }
297                return;
298            }
299            for (Policy policy : sPolicies) {
300                String seInfo = policy.getMatchedSeInfo(pkg);
301                if (seInfo != null) {
302                    pkg.applicationInfo.seInfo = seInfo;
303                    break;
304                }
305            }
306        }
307
308        if (pkg.applicationInfo.targetSandboxVersion == 2)
309            pkg.applicationInfo.seInfo += SANDBOX_V2_STR;
310
311        if (isPrivileged) {
312            pkg.applicationInfo.seInfo += PRIVILEGED_APP_STR;
313        }
314
315        pkg.applicationInfo.seInfo += TARGETSDKVERSION_STR + targetSdkVersion;
316
317        if (DEBUG_POLICY_INSTALL) {
318            Slog.i(TAG, "package (" + pkg.packageName + ") labeled with " +
319                    "seinfo=" + pkg.applicationInfo.seInfo);
320        }
321    }
322}
323
324/**
325 * Holds valid policy representations of individual stanzas from a mac_permissions.xml
326 * file. Each instance can further be used to assign seinfo values to apks using the
327 * {@link Policy#getMatchedSeinfo} method. To create an instance of this use the
328 * {@link PolicyBuilder} pattern class, where each instance is validated against a set
329 * of invariants before being built and returned. Each instance can be guaranteed to
330 * hold one valid policy stanza as outlined in the system/sepolicy/mac_permissions.xml
331 * file.
332 * <p>
333 * The following is an example of how to use {@link Policy.PolicyBuilder} to create a
334 * signer based Policy instance with only inner package name refinements.
335 * </p>
336 * <pre>
337 * {@code
338 * Policy policy = new Policy.PolicyBuilder()
339 *         .addSignature("308204a8...")
340 *         .addSignature("483538c8...")
341 *         .addInnerPackageMapOrThrow("com.foo.", "bar")
342 *         .addInnerPackageMapOrThrow("com.foo.other", "bar")
343 *         .build();
344 * }
345 * </pre>
346 * <p>
347 * The following is an example of how to use {@link Policy.PolicyBuilder} to create a
348 * signer based Policy instance with only a global seinfo tag.
349 * </p>
350 * <pre>
351 * {@code
352 * Policy policy = new Policy.PolicyBuilder()
353 *         .addSignature("308204a8...")
354 *         .addSignature("483538c8...")
355 *         .setGlobalSeinfoOrThrow("paltform")
356 *         .build();
357 * }
358 * </pre>
359 */
360final class Policy {
361
362    private final String mSeinfo;
363    private final Set<Signature> mCerts;
364    private final Map<String, String> mPkgMap;
365
366    // Use the PolicyBuilder pattern to instantiate
367    private Policy(PolicyBuilder builder) {
368        mSeinfo = builder.mSeinfo;
369        mCerts = Collections.unmodifiableSet(builder.mCerts);
370        mPkgMap = Collections.unmodifiableMap(builder.mPkgMap);
371    }
372
373    /**
374     * Return all the certs stored with this policy stanza.
375     *
376     * @return A set of Signature objects representing all the certs stored
377     *         with the policy.
378     */
379    public Set<Signature> getSignatures() {
380        return mCerts;
381    }
382
383    /**
384     * Return whether this policy object contains package name mapping refinements.
385     *
386     * @return A boolean indicating if this object has inner package name mappings.
387     */
388    public boolean hasInnerPackages() {
389        return !mPkgMap.isEmpty();
390    }
391
392    /**
393     * Return the mapping of all package name refinements.
394     *
395     * @return A Map object whose keys are the package names and whose values are
396     *         the seinfo assignments.
397     */
398    public Map<String, String> getInnerPackages() {
399        return mPkgMap;
400    }
401
402    /**
403     * Return whether the policy object has a global seinfo tag attached.
404     *
405     * @return A boolean indicating if this stanza has a global seinfo tag.
406     */
407    public boolean hasGlobalSeinfo() {
408        return mSeinfo != null;
409    }
410
411    @Override
412    public String toString() {
413        StringBuilder sb = new StringBuilder();
414        for (Signature cert : mCerts) {
415            sb.append("cert=" + cert.toCharsString().substring(0, 11) + "... ");
416        }
417
418        if (mSeinfo != null) {
419            sb.append("seinfo=" + mSeinfo);
420        }
421
422        for (String name : mPkgMap.keySet()) {
423            sb.append(" " + name + "=" + mPkgMap.get(name));
424        }
425
426        return sb.toString();
427    }
428
429    /**
430     * <p>
431     * Determine the seinfo value to assign to an apk. The appropriate seinfo value
432     * is determined using the following steps:
433     * </p>
434     * <ul>
435     *   <li> All certs used to sign the apk and all certs stored with this policy
436     *     instance are tested for set equality. If this fails then null is returned.
437     *   </li>
438     *   <li> If all certs match then an appropriate inner package stanza is
439     *     searched based on package name alone. If matched, the stored seinfo
440     *     value for that mapping is returned.
441     *   </li>
442     *   <li> If all certs matched and no inner package stanza matches then return
443     *     the global seinfo value. The returned value can be null in this case.
444     *   </li>
445     * </ul>
446     * <p>
447     * In all cases, a return value of null should be interpreted as the apk failing
448     * to match this Policy instance; i.e. failing this policy stanza.
449     * </p>
450     * @param pkg the apk to check given as a PackageParser.Package object
451     * @return A string representing the seinfo matched during policy lookup.
452     *         A value of null can also be returned if no match occured.
453     */
454    public String getMatchedSeInfo(PackageParser.Package pkg) {
455        // Check for exact signature matches across all certs.
456        Signature[] certs = mCerts.toArray(new Signature[0]);
457        if (pkg.mSigningDetails != SigningDetails.UNKNOWN
458                && !Signature.areExactMatch(certs, pkg.mSigningDetails.signatures)) {
459            return null;
460        }
461
462        // Check for inner package name matches given that the
463        // signature checks already passed.
464        String seinfoValue = mPkgMap.get(pkg.packageName);
465        if (seinfoValue != null) {
466            return seinfoValue;
467        }
468
469        // Return the global seinfo value.
470        return mSeinfo;
471    }
472
473    /**
474     * A nested builder class to create {@link Policy} instances. A {@link Policy}
475     * class instance represents one valid policy stanza found in a mac_permissions.xml
476     * file. A valid policy stanza is defined to be a signer stanza which obeys the rules
477     * outlined in system/sepolicy/mac_permissions.xml. The {@link #build} method
478     * ensures a set of invariants are upheld enforcing the correct stanza structure
479     * before returning a valid Policy object.
480     */
481    public static final class PolicyBuilder {
482
483        private String mSeinfo;
484        private final Set<Signature> mCerts;
485        private final Map<String, String> mPkgMap;
486
487        public PolicyBuilder() {
488            mCerts = new HashSet<Signature>(2);
489            mPkgMap = new HashMap<String, String>(2);
490        }
491
492        /**
493         * Adds a signature to the set of certs used for validation checks. The purpose
494         * being that all contained certs will need to be matched against all certs
495         * contained with an apk.
496         *
497         * @param cert the signature to add given as a String.
498         * @return The reference to this PolicyBuilder.
499         * @throws IllegalArgumentException if the cert value fails validation;
500         *         null or is an invalid hex-encoded ASCII string.
501         */
502        public PolicyBuilder addSignature(String cert) {
503            if (cert == null) {
504                String err = "Invalid signature value " + cert;
505                throw new IllegalArgumentException(err);
506            }
507
508            mCerts.add(new Signature(cert));
509            return this;
510        }
511
512        /**
513         * Set the global seinfo tag for this policy stanza. The global seinfo tag
514         * when attached to a signer tag represents the assignment when there isn't a
515         * further inner package refinement in policy.
516         *
517         * @param seinfo the seinfo value given as a String.
518         * @return The reference to this PolicyBuilder.
519         * @throws IllegalArgumentException if the seinfo value fails validation;
520         *         null, zero length or contains non-valid characters [^a-zA-Z_\._0-9].
521         * @throws IllegalStateException if an seinfo value has already been found
522         */
523        public PolicyBuilder setGlobalSeinfoOrThrow(String seinfo) {
524            if (!validateValue(seinfo)) {
525                String err = "Invalid seinfo value " + seinfo;
526                throw new IllegalArgumentException(err);
527            }
528
529            if (mSeinfo != null && !mSeinfo.equals(seinfo)) {
530                String err = "Duplicate seinfo tag found";
531                throw new IllegalStateException(err);
532            }
533
534            mSeinfo = seinfo;
535            return this;
536        }
537
538        /**
539         * Create a package name to seinfo value mapping. Each mapping represents
540         * the seinfo value that will be assigned to the described package name.
541         * These localized mappings allow the global seinfo to be overriden.
542         *
543         * @param pkgName the android package name given to the app
544         * @param seinfo the seinfo value that will be assigned to the passed pkgName
545         * @return The reference to this PolicyBuilder.
546         * @throws IllegalArgumentException if the seinfo value fails validation;
547         *         null, zero length or contains non-valid characters [^a-zA-Z_\.0-9].
548         *         Or, if the package name isn't a valid android package name.
549         * @throws IllegalStateException if trying to reset a package mapping with a
550         *         different seinfo value.
551         */
552        public PolicyBuilder addInnerPackageMapOrThrow(String pkgName, String seinfo) {
553            if (!validateValue(pkgName)) {
554                String err = "Invalid package name " + pkgName;
555                throw new IllegalArgumentException(err);
556            }
557            if (!validateValue(seinfo)) {
558                String err = "Invalid seinfo value " + seinfo;
559                throw new IllegalArgumentException(err);
560            }
561
562            String pkgValue = mPkgMap.get(pkgName);
563            if (pkgValue != null && !pkgValue.equals(seinfo)) {
564                String err = "Conflicting seinfo value found";
565                throw new IllegalStateException(err);
566            }
567
568            mPkgMap.put(pkgName, seinfo);
569            return this;
570        }
571
572        /**
573         * General validation routine for the attribute strings of an element. Checks
574         * if the string is non-null, positive length and only contains [a-zA-Z_\.0-9].
575         *
576         * @param name the string to validate.
577         * @return boolean indicating if the string was valid.
578         */
579        private boolean validateValue(String name) {
580            if (name == null)
581                return false;
582
583            // Want to match on [0-9a-zA-Z_.]
584            if (!name.matches("\\A[\\.\\w]+\\z")) {
585                return false;
586            }
587
588            return true;
589        }
590
591        /**
592         * <p>
593         * Create a {@link Policy} instance based on the current configuration. This
594         * method checks for certain policy invariants used to enforce certain guarantees
595         * about the expected structure of a policy stanza.
596         * Those invariants are:
597         * </p>
598         * <ul>
599         *   <li> at least one cert must be found </li>
600         *   <li> either a global seinfo value is present OR at least one
601         *     inner package mapping must be present BUT not both. </li>
602         * </ul>
603         * @return an instance of {@link Policy} with the options set from this builder
604         * @throws IllegalStateException if an invariant is violated.
605         */
606        public Policy build() {
607            Policy p = new Policy(this);
608
609            if (p.mCerts.isEmpty()) {
610                String err = "Missing certs with signer tag. Expecting at least one.";
611                throw new IllegalStateException(err);
612            }
613            if (!(p.mSeinfo == null ^ p.mPkgMap.isEmpty())) {
614                String err = "Only seinfo tag XOR package tags are allowed within " +
615                        "a signer stanza.";
616                throw new IllegalStateException(err);
617            }
618
619            return p;
620        }
621    }
622}
623
624/**
625 * Comparision imposing an ordering on Policy objects. It is understood that Policy
626 * objects can only take one of three forms and ordered according to the following
627 * set of rules most specific to least.
628 * <ul>
629 *   <li> signer stanzas with inner package mappings </li>
630 *   <li> signer stanzas with global seinfo tags </li>
631 * </ul>
632 * This comparison also checks for duplicate entries on the input selectors. Any
633 * found duplicates will be flagged and can be checked with {@link #foundDuplicate}.
634 */
635
636final class PolicyComparator implements Comparator<Policy> {
637
638    private boolean duplicateFound = false;
639
640    public boolean foundDuplicate() {
641        return duplicateFound;
642    }
643
644    @Override
645    public int compare(Policy p1, Policy p2) {
646
647        // Give precedence to stanzas with inner package mappings
648        if (p1.hasInnerPackages() != p2.hasInnerPackages()) {
649            return p1.hasInnerPackages() ? -1 : 1;
650        }
651
652        // Check for duplicate entries
653        if (p1.getSignatures().equals(p2.getSignatures())) {
654            // Checks if signer w/o inner package names
655            if (p1.hasGlobalSeinfo()) {
656                duplicateFound = true;
657                Slog.e(SELinuxMMAC.TAG, "Duplicate policy entry: " + p1.toString());
658            }
659
660            // Look for common inner package name mappings
661            final Map<String, String> p1Packages = p1.getInnerPackages();
662            final Map<String, String> p2Packages = p2.getInnerPackages();
663            if (!Collections.disjoint(p1Packages.keySet(), p2Packages.keySet())) {
664                duplicateFound = true;
665                Slog.e(SELinuxMMAC.TAG, "Duplicate policy entry: " + p1.toString());
666            }
667        }
668
669        return 0;
670    }
671}
672