Commits

Stephen Smalley committed 4c7ff8b

Add setool and build_bundle toolsuite.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>

  • Participants
  • Parent commits af448cd
  • Branches seandroid-4.4.2

Comments (0)

Files changed (19)

-This configuration (sepolicy) is public domain, i.e. not copyrighted.
+All of the configuration files within this directory are public domain,
+i.e. not copyrighted.
+
+Specific files under the tools subdirectory are derived from the
+Android Open Source Project (http://source.android.com) and are therefore
+licensed under the Apache License, Version 2.0.  At present this is only
+true for the following file:
+	tools/build_bundle/src/android/util/Base64.java
+See the individual files for specific information.  If not otherwise marked,
+the files are public domain.
 
 Warranty Exclusion
 ------------------
 limitation will apply even if NSA has been advised of the possibility
 of such damage. You acknowledge that this is a reasonable allocation of
 risk.
+
+                               Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+
+
+UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
+
+Unicode Data Files include all data files under the directories
+http://www.unicode.org/Public/, http://www.unicode.org/reports/,
+and http://www.unicode.org/cldr/data/ . Unicode Software includes any
+source code published in the Unicode Standard or under the directories
+http://www.unicode.org/Public/, http://www.unicode.org/reports/, and
+http://www.unicode.org/cldr/data/.
+
+NOTICE TO USER: Carefully read the following legal agreement. BY
+DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA
+FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY
+ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF
+THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY,
+DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright © 1991-2008 Unicode, Inc. All rights reserved. Distributed
+under the Terms of Use in http://www.unicode.org/copyright.html.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Unicode data files and any associated documentation (the
+"Data Files") or Unicode software and any associated documentation (the
+"Software") to deal in the Data Files or Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, and/or sell copies of the Data Files or Software,
+and to permit persons to whom the Data Files or Software are furnished to
+do so, provided that (a) the above copyright notice(s) and this permission
+notice appear with all copies of the Data Files or Software, (b) both the
+above copyright notice(s) and this permission notice appear in associated
+documentation, and (c) there is clear notice in each modified Data File
+or in the Software as well as in the documentation associated with the
+Data File(s) or Software that the data or software has been modified.
+
+THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
+INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
+OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
+OR PERFORMANCE OF THE DATA FILES OR SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder
+shall not be used in advertising or otherwise to promote the sale, use
+or other dealings in these Data Files or Software without prior written
+authorization of the copyright holder.
+
 LOCAL_MODULE_TAGS := optional
 
 include $(BUILD_PREBUILT)
+
 ###################################
 include $(CLEAR_VARS)
 
 LOCAL_STATIC_LIBRARIES := libsepol
 
 include $(BUILD_HOST_EXECUTABLE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))

tools/build_bundle/Android.mk

+LOCAL_PATH := $(call my-dir)
+
+#################################
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := buildbundle
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+	$(call all-java-files-under, src) \
+	../../../../frameworks/base/core/java/android/util/Base64.java
+
+LOCAL_JAR_MANIFEST := BuildBundle.mf
+
+LOCAL_STATIC_JAVA_LIBRARIES := guavalib
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+##################################
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_PREBUILT_EXECUTABLES := buildbundle
+
+include $(BUILD_HOST_PREBUILT)
+
+##################################
+include $(CLEAR_VARS)
+
+LOCAL_REQUIRED_MODULES := buildbundle
+LOCAL_MODULE := buildsebundle
+LOCAL_SRC_FILES := buildsebundle
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_IS_HOST_MODULE := true
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_PREBUILT)
+
+##################################
+include $(CLEAR_VARS)
+
+LOCAL_REQUIRED_MODULES := buildbundle
+LOCAL_MODULE := buildeopbundle
+LOCAL_SRC_FILES := buildeopbundle
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_IS_HOST_MODULE := true
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_PREBUILT)
+
+##################################
+include $(CLEAR_VARS)
+
+LOCAL_REQUIRED_MODULES := buildbundle
+LOCAL_MODULE := buildpermsbundle
+LOCAL_SRC_FILES := buildpermsbundle
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_IS_HOST_MODULE := true
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_PREBUILT)
+##################################
+include $(CLEAR_VARS)
+
+LOCAL_REQUIRED_MODULES := buildbundle
+LOCAL_MODULE := buildifwbundle
+LOCAL_SRC_FILES := buildifwbundle
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_IS_HOST_MODULE := true
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_PREBUILT)

tools/build_bundle/BuildBundle.mf

+Main-Class: com.android.buildbundle.BuildBundle

tools/build_bundle/buildbundle

+#!/bin/sh
+
+prog="$0"
+progdir=`dirname "${prog}"`
+
+jarfile=buildbundle.jar
+frameworkdir="$progdir"
+
+if [ ! -r "$frameworkdir/$jarfile" ]; then
+    frameworkdir=`dirname "$progdir"`/framework
+fi
+if [ ! -r "$frameworkdir/$jarfile" ]; then
+    root="${ANDROID_BUILD_TOP}"
+    if [ -z $root ]; then
+        echo "ANDROID_BUILD_TOP var not found. Trying running 'lunch' command first."
+        exit 1
+    fi
+    root=$root"/out/host"
+    spot="."
+    uname=`uname -a`
+    mac=$(echo $uname | grep "Darwin")
+    if [ -n mac ]; then
+        mac_type=$(echo $uname | grep -e "i386" -e "x86_64")
+        if [ -n mac_type ]; then
+            spot="darwin-x86"
+        else
+            spot="darwin-ppc"
+        fi
+    fi
+    linux=$(echo $uname | grep "Linux")
+    if [ -n linux ]; then
+        spot="linux-x86"
+    fi
+    frameworkdir="$root"/"$spot"/framework
+fi
+if [ ! -r "$frameworkdir/$jarfile" ]; then
+    echo `basename "$prog"`": can't find $jarfile"
+    echo "Make sure buildbundle.jar has been built."
+    exit 1
+fi
+
+jarpath="$frameworkdir/$jarfile"
+
+exec java -Xmx128M -jar "$jarpath" "$@"

tools/build_bundle/buildeopbundle

+#!/bin/sh
+
+##
+# A simple wrapper script around buildbundle that builds
+# a zip file to deliver the eops policy file.
+
+usage()
+{
+cat << EOF
+
+usage: buildeopbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
+[-h] -- <eops.xml>
+
+This script builds a eops policy bundle and supporting
+metadata file capable of being loaded via the ConfigUpdate
+mechanism. It takes a pkcs8 DER encoded RSA private key
+that is then used to sign the bundle. For AOSP development
+you'll typically want to use the key from the source tree at
+build/target/product/security/testkey.pk8. If building
+your own cert you should probably use a key size of at least
+1024 or greater. The bundle requires that the eops.xml
+file be included and with that exact basename. The built
+bundle will be written to eop_bundle.zip which will include
+the signature metadata file of the bundle.
+
+OPTIONS:
+   -h      Show this message.
+   -v      Version of the built bundle. Defaults to 1.
+   -r      SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
+
+EOF
+}
+
+VERSION="1"
+HASH="NONE"
+KEY=
+EOPS=
+OUTPUT=eops_bundle.zip
+while getopts "k:v:r:h" OPTION
+do
+     case $OPTION in
+         k)
+             KEY=$OPTARG
+             ;;
+         v)
+             VERSION=$OPTARG
+             ;;
+         r)
+             HASH=$OPTARG
+             ;;
+         h)
+             usage
+             exit 1
+             ;;
+         ?)
+             usage
+             exit 1
+             ;;
+     esac
+done
+
+shift $((OPTIND-1))
+
+# Infer from the basenames the correct eops policy
+for POLICY in $@
+do
+    case `basename $POLICY` in
+        eops.xml)
+            EOPS=$POLICY
+            ;;
+        ?)
+            # intentionally ignore?
+            ;;
+    esac
+done
+
+# We require eops.xml and the private key to both be present.
+if [ -z $EOPS ] || [ -z $KEY ]
+then
+     usage
+     exit 1
+fi
+
+BUILDBUNDLE_COMMAND="buildbundle -k $KEY -v $VERSION -r $HASH -o $OUTPUT -e none $EOPS"
+$BUILDBUNDLE_COMMAND

tools/build_bundle/buildifwbundle

+#!/bin/sh
+
+##
+# A simple wrapper script around buildbundle that builds
+# a zip file to deliver the intent firewall policy file.
+
+usage()
+{
+cat << EOF
+
+usage: buildifwbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
+[-h] -- <ifw.xml>
+
+This script builds an intent firewall policy bundle and supporting
+metadata file capable of being loaded via the ConfigUpdate
+mechanism. It takes a pkcs8 DER encoded RSA private key
+that is then used to sign the bundle. For AOSP development
+you'll typically want to use the key from the source tree at
+build/target/product/security/testkey.pk8. If building
+your own cert you should probably use a key size of at least
+1024 or greater. The bundle requires that the ifw.xml
+file be included and with that exact basename. The built
+bundle will be written to ifw_bundle.zip which will include
+the signature metadata file of the bundle.
+
+OPTIONS:
+   -h      Show this message.
+   -v      Version of the built bundle. Defaults to 1.
+   -r      SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
+
+EOF
+}
+
+VERSION="1"
+HASH="NONE"
+KEY=
+IFW=
+OUTPUT=ifw_bundle.zip
+while getopts "k:v:r:h" OPTION
+do
+     case $OPTION in
+         k)
+             KEY=$OPTARG
+             ;;
+         v)
+             VERSION=$OPTARG
+             ;;
+         r)
+             HASH=$OPTARG
+             ;;
+         h)
+             usage
+             exit 1
+             ;;
+         ?)
+             usage
+             exit 1
+             ;;
+     esac
+done
+
+shift $((OPTIND-1))
+
+# Infer from the basenames the correct ifw policy
+for POLICY in $@
+do
+    case `basename $POLICY` in
+        ifw.xml)
+            IFW=$POLICY
+            ;;
+        ?)
+            # intentionally ignore?
+            ;;
+    esac
+done
+
+# We require ifw.xml and the private key to both be present.
+if [ -z $IFW ] || [ -z $KEY ]
+then
+     usage
+     exit 1
+fi
+
+BUILDBUNDLE_COMMAND="buildbundle -k $KEY -v $VERSION -r $HASH -o $OUTPUT -e none $IFW"
+$BUILDBUNDLE_COMMAND

tools/build_bundle/buildpermsbundle

+#!/bin/sh
+
+##
+# A simple wrapper script around buildbundle that builds
+# a zip file to deliver the mac_permissions.xml policy file.
+
+usage()
+{
+cat << EOF
+
+usage: buildpermsbundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
+[-h] -- <mac_permissions.xml>
+
+This script builds a mac_permissions policy bundle and supporting
+metadata file capable of being loaded via the ConfigUpdate
+mechanism. It takes a pkcs8 DER encoded RSA private key
+that is then used to sign the bundle. For AOSP development
+you'll typically want to use the key from the source tree at
+build/target/product/security/testkey.pk8. If building
+your own cert you should probably use a key size of at least
+1024 or greater. The bundle requires that the mac_permissions.xml
+file be included and with that exact basename. The built
+bundle will be written to mac_perms_bundle.zip which will include
+the signature metadata file of the bundle.
+
+OPTIONS:
+   -h      Show this message.
+   -v      Version of the built bundle. Defaults to 1.
+   -r      SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
+
+EOF
+}
+
+VERSION="1"
+HASH="NONE"
+KEY=
+MAC_PERMS=
+OUTPUT=mac_perms_bundle.zip
+while getopts "k:v:r:h" OPTION
+do
+     case $OPTION in
+         k)
+             KEY=$OPTARG
+             ;;
+         v)
+             VERSION=$OPTARG
+             ;;
+         r)
+             HASH=$OPTARG
+             ;;
+         h)
+             usage
+             exit 1
+             ;;
+         ?)
+             usage
+             exit 1
+             ;;
+     esac
+done
+
+shift $((OPTIND-1))
+
+# Infer from the basenames the correct eops policy
+for POLICY in $@
+do
+    case `basename $POLICY` in
+        mac_permissions.xml)
+            MAC_PERMS=$POLICY
+            ;;
+        ?)
+            # intentionally ignore?
+            ;;
+    esac
+done
+
+# We require eops.xml and the private key to both be present.
+if [ -z $MAC_PERMS ] || [ -z $KEY ]
+then
+     usage
+     exit 1
+fi
+
+BUILDBUNDLE_COMMAND="buildbundle -k $KEY -v $VERSION -r $HASH -o $OUTPUT -e none $MAC_PERMS"
+$BUILDBUNDLE_COMMAND

tools/build_bundle/buildsebundle

+#!/bin/sh
+
+##
+# A simple wrapper script around buildbundle that puts
+# the selinux policy files in the correct order as well
+# as correctly labels the output zip file. buildbundle
+# is not context aware w.r.t the correct ordering of
+# selinux files and so this wrapper script is needed.
+#
+
+usage()
+{
+cat << EOF
+
+usage: buildsebundle -k <private key.pk8> [-v <version>] [-r <previous hash>] \
+[-h] -- <file_contexts> <property_contexts> <sepolicy> <seapp_contexts>
+
+This script builds a selinux policy bundle and supporting
+metadata file capable of being loaded via the ConfigUpdate
+mechanism. It takes a pkcs8 DER encoded RSA private key
+that is then used to sign the bundle. For AOSP development
+you'll typically want to use the key from the source tree at
+build/target/product/security/testkey.pk8. If building
+your own cert you should probably use a key size of at least
+1024 or greater. The bundle requires that seapp_contexts,
+file_contexts, property_contexts and sepolicy files all be
+included and with those exact basenames. The built bundle will
+be written to selinux_bundle.zip which will include the
+signature metadata file of the bundle.
+
+OPTIONS:
+   -h      Show this message.
+   -v      Version of the built bundle. Defaults to 1.
+   -r      SHA-512 hash of the bundle to replace. Defaults to 'NONE'.
+
+EOF
+}
+
+VERSION="1"
+HASH="NONE"
+KEY=
+FILE_CONTEXTS=
+PROPERTY_CONTEXTS=
+SEAPP_CONTEXTS=
+SEPOLICY=
+ENFORCE="0"
+OUTPUT=selinux_bundle.zip
+while getopts "k:v:r:h" OPTION
+do
+     case $OPTION in
+         k)
+             KEY=$OPTARG
+             ;;
+         v)
+             VERSION=$OPTARG
+             ;;
+         r)
+             HASH=$OPTARG
+             ;;
+         h)
+             usage
+             exit 1
+             ;;
+         ?)
+             usage
+             exit 1
+             ;;
+     esac
+done
+
+shift $((OPTIND-1))
+
+# Infer from the basenames the correct selinux policy
+for POLICY in $@
+do
+    case `basename $POLICY` in
+        seapp_contexts)
+            SEAPP_CONTEXTS=$POLICY
+            ;;
+        file_contexts)
+            FILE_CONTEXTS=$POLICY
+            ;;
+        property_contexts)
+            PROPERTY_CONTEXTS=$POLICY
+            ;;
+        sepolicy)
+            SEPOLICY=$POLICY
+            ;;
+        ?)
+            # intentionally ignore?
+            ;;
+    esac
+done
+
+# We require seapp_contexts, file_contexts, property_contexts, sepolicy
+# and the private key to all be present.
+if [ -z $FILE_CONTEXTS ] || [ -z $PROPERTY_CONTEXTS ] || [ -z $SEAPP_CONTEXTS ] \
+   || [ -z $SEPOLICY ] || [ -z $KEY ]
+then
+     usage
+     exit 1
+fi
+
+# Notice the order of the policy files matter here. The backend expects
+# a set order. Any change there (SELinuxPolicyInstallReceiver.java) will
+# result in a change here.
+BUILDBUNDLE_COMMAND="buildbundle -k $KEY -v $VERSION -r $HASH -o $OUTPUT $SEAPP_CONTEXTS $PROPERTY_CONTEXTS $FILE_CONTEXTS $SEPOLICY"
+$BUILDBUNDLE_COMMAND

tools/build_bundle/src/com/android/buildbundle/BuildBundle.java

+package com.android.buildbundle;
+
+import com.android.buildbundle.Encoding.*;
+
+import com.google.common.base.Joiner;
+import com.google.common.io.ByteStreams;
+import com.google.common.io.Closeables;
+import com.google.common.io.Files;
+
+import java.lang.InterruptedException;
+import java.lang.Process;
+import java.lang.ProcessBuilder;
+
+import java.io.*;
+
+import java.security.*;
+import java.security.spec.KeySpec;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
+
+import javax.crypto.Cipher;
+import javax.crypto.EncryptedPrivateKeyInfo;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+
+import java.util.ArrayList;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+import android.util.Base64;
+
+/**
+ * Command line tool to build OTA config bundles capable of
+ * being delivered via the ConfigUpdateInstallReceiver
+ * mechanism.
+ *
+ * <pre>
+ * Usage: buildbundle -k &lt;privatekey.pk8&gt; [-v &lt;version&gt;] [-r &lt;required hash&gt;] 
+ *                    [-o &lt;output zip file&gt;] [-m &lt;meta&gt;] [-e &lt;encoding&gt;] [-h]
+ *                    file [ file [ file ... ] ]
+ * Options:
+ *    -k pkcs8 DER formatted private key used to sign the bundle.
+ *    -v version of the created bundle. Defaults to 1.
+ *    -r hash of previous bundle that will be replaced. Defaults to 'NONE'.
+ *    -o name of the output zip file. Defaults to update_bundle.zip.
+ *    -e type of bundle encoding. Possible values are 'base64' and 'none'.
+ *       Defaults to 'base64'.
+ *    -m an optional value that will be appended to the metadata file.
+ *    -h prints this help screen.
+ * Positional Arguments:
+ *    file: path to a file to be included in the signed bundle.
+ *          The order of the files will be preserved in the bundle.
+ * </pre>
+ */
+public class BuildBundle {
+
+    /**
+     * Print a usage statement prepended with a header string
+     * and then exit with a value of 1.
+     *
+     * @param header a string that will be printed before
+     *        the usage statement.
+     */
+    private static void usage(String header) {
+        System.err.println("\n" + header + "\n");
+        System.err.println("Usage: buildbundle -k <privatekey.pk8> " +
+                           "[-v <version>] [-r <required hash>] " +
+                           "[-o <output zip file>] [-m <meta>] [-e <encoding>] " +
+                           "[-h] file [ file [ file ... ] ] ");
+        System.err.println("Options:");
+        System.err.println(" -k pkcs8 DER formatted private key used to sign the bundle.");
+        System.err.println(" -v version of the created bundle. Defaults to 1.");
+        System.err.println(" -r hash of previous bundle that will be replaced. Defaults to 'NONE'.");
+        System.err.println(" -o name of the output zip file. Defaults to update_bundle.zip.");
+        System.err.println(" -m additional value that will be appended to the metadata file.");
+        System.err.println(" -e type of bundle encoding. Possible values are 'base64' and 'none'.");
+        System.err.println("    Defaults to 'base64'.");
+        System.err.println(" -h prints this help screen.");
+        System.err.println("Positional Arguments:");
+        System.err.println(" file: path to a file to be included in the signed bundle.");
+        System.err.println("       The order of the files will be preserved in the bundle.");
+        System.exit(1);
+    }
+
+    /**
+     * Given an array of paths to files, create a bundle
+     * capable of being loaded via the ConfigUpdateInstallReceiver
+     * mechanism. The order of the entries in the array will
+     * be preserved when building the bundle. The bundle as
+     * a byte array is returned and is capable of being directly
+     * loaded via the ConfigUpdateInstallReceiver mechanism.
+     * The format of the returned bundle depends on the number of
+     * passed paths. If more than one file is passed then a
+     * header representing file lengths will precede the file
+     * contents. If only one file is passed then no byte header
+     * is attached. If there are no paths passed then no bundle
+     * is created; however, an empty byte array will still be
+     * returned. No metadata about the bundle is returned;
+     * additional processing must be performed to calculate that
+     * data.
+     *
+     * @param paths ArrayList of strings representing paths
+     *              to config files to include in the bundle.
+     * @param encodingFunction the scheme used to encode
+     *        the bundle.
+     *
+     * @exception IOException produced by failed or interrupted
+     *            I/O operations on any of the requested paths.
+     *            Also thrown if the passed paths list is null
+     *            or the encoding scheme is null.
+     *
+     * @return byte array of the created config bundle.
+     */
+    public static byte[] build_bundle(ArrayList<String> paths, Encoding encodingFunction)
+            throws IOException {
+
+        if (paths == null) {
+            throw new IOException("Requested paths is null");
+        }
+
+        if (encodingFunction == null) {
+            throw new IOException("Encoding scheme is null");
+        }
+
+        int numOfPaths = paths.size();
+        int[] lengths = new int[numOfPaths];
+        byte[][] files = new byte[numOfPaths][];
+
+        for (int i = 0; i < numOfPaths; i++) {
+            files[i] = encodingFunction.create_encoding(new File(paths.get(i)));
+            lengths[i] = files[i].length;
+        }
+
+        ByteBuffer b = ByteBuffer.allocate(numOfPaths * 4);
+        for (int i = 0; i < numOfPaths; i++) {
+            b.putInt(lengths[i]);
+        }
+
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        if (numOfPaths > 1) {
+            output.write(b.array());
+        }
+        for (int i = 0; i < numOfPaths; i++) {
+            output.write(files[i]);
+        }
+
+        return output.toByteArray();
+    }
+
+    /**
+     * Prompt the user for a password. The password isn't
+     * echoed back to the screen and is returned as a
+     * char array. This function assumes there is a console
+     * device associated with the current JVM. This might not
+     * be the case, for instance if started by a background job
+     * scheduler. Thus, this function might have to change
+     * in the future.
+     *
+     * @param keyPath the path to the key as a string.
+     *
+     * @exception IOException produced by failed or interrupted
+     *            I/O operations on the current console.
+     *
+     * @return a char array of the password needed to decrypt
+     *         the key or null if an error occured with the console.
+     */
+    private static char[] getPassword(String keyPath) throws IOException {
+
+        char[] password = null;
+        Console cons = System.console();
+        if (cons != null) {
+            final String con = "Enter password for " + keyPath;
+            password = cons.readPassword("%s> ", con);
+        }
+
+        return password;
+    }
+
+    /**
+     * Based on ghstark's post on Aug 6, 2006 at
+     * http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949
+     *
+     * Convert a pkcs8 formatted private key into a PrivateKey
+     * interface object. The private key can be encrypted or not.
+     * If encrypted, the user will be prompted for the password.
+     *
+     * @param privateKey the private key to decrypt given as byte array.
+     * @param keyPath path to the key given as a string.
+     *
+     * @exception IOException produced by failed or interrupted I/O
+     *            operations when retrieving the password for the key.
+     * @exception GeneralSecurityException generic security exceptions
+     *            that result from signature and key operations.
+     *
+     * @return a KeySpec object which can be used to derive additional
+     *         key material if the passed private key is encrypted. If
+     *         the private key isn't encrypted then null is returned.
+     */
+    private static KeySpec decryptPrivateKey(byte[] privateKey, String keyFile)
+            throws IOException, GeneralSecurityException {
+
+        EncryptedPrivateKeyInfo epkInfo;
+        try {
+            epkInfo = new EncryptedPrivateKeyInfo(privateKey);
+        } catch (IOException ex) {
+            // Probably not an encrypted key.
+            return null;
+        }
+
+        char[] password = getPassword(keyFile);
+
+        SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
+        Key key = skFactory.generateSecret(new PBEKeySpec(password));
+
+        Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
+        cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());
+
+        try {
+            return epkInfo.getKeySpec(cipher);
+        } catch (InvalidKeySpecException ex) {
+            System.err.println("Password for " + keyFile + " may be bad.");
+            throw new GeneralSecurityException(ex);
+        }
+    }
+
+    /**
+     * Return a PrivateKey object of the private key after being
+     * decrypted with a password if needed. The private key is
+     * assumed to be encoded according to the pkcs8 standard.
+     *
+     * @param privateKey the private key to decrypt given as byte array.
+     * @param keyPath path to the key given as a string.
+     *
+     * @exception IOException produced by failed or interrupted I/O
+     *            operations when retrieving the password for the key.
+     * @exception GeneralSecurityException generic security exceptions
+     *            that result from signature and key operations.
+     *
+     * @return a PrivateKey interface object to the underlying
+     *         key material.
+     */
+    private static PrivateKey getPrivateKey(byte[] privateKey, String keyPath)
+            throws IOException, GeneralSecurityException {
+
+        KeySpec spec = decryptPrivateKey(privateKey, keyPath);
+        if (spec == null) {
+            spec = new PKCS8EncodedKeySpec(privateKey);
+        }
+
+        try {
+            return KeyFactory.getInstance("RSA").generatePrivate(spec);
+        } catch (InvalidKeySpecException ex) {
+            System.err.println(keyPath + " probably not a PKCS#8 DER formatted RSA cert.");
+            throw new GeneralSecurityException(ex);
+        }
+    }
+
+    /**
+     * Takes a byte array as well as the version, previous hash and
+     * optional meta value and computes the digital signature using
+     * RSA and SHA-512. The secured message is then returned as a
+     * byte array.
+     *
+     * @param bundle byte array representing the built config bundle.
+     * @param version the version of this config update.
+     * @param privKey the path to the pkcs8 DER formatted private key
+     *                used to sign the config update.
+     * @param requiredHash the hash of the previous config update
+     *                     that will be replaced.
+     * @param otherMeta a generic string that will be added to the
+     *                  signed bundle. If the string is null it
+     *                  will not be part of the signed bundle.
+     *
+     * @exception IOException produced by failed or interrupted
+     *            I/O operations when retrieving the key.
+     * @exception GeneralSecurityException generic security exceptions
+     *            that result from signature and hashing attempts.
+     *
+     * @return a byte array of the signed message.
+     */
+    public static byte[] sign_bundle(byte[] bundle, String version, String privKey,
+                                     String requiredHash, String otherMeta)
+            throws IOException, GeneralSecurityException {
+
+        InputStream is = new FileInputStream(new File (privKey));
+        byte[] privateKey = ByteStreams.toByteArray(is);
+        is.close();
+        PrivateKey pk = getPrivateKey(privateKey, privKey);
+
+        Signature signer = Signature.getInstance("SHA512withRSA");
+        signer.initSign(pk);
+        signer.update(bundle);
+        signer.update(version.getBytes());
+        signer.update(requiredHash.getBytes());
+        if (otherMeta != null) {
+            signer.update(otherMeta.getBytes());
+        }
+
+        // The signature should be one large string
+        return Base64.encode(signer.sign(), Base64.NO_WRAP);
+    }
+
+    /**
+     * Runs the command line driver.
+     *
+     * @param args program arguments.
+     */
+    public static void main(String[] args) {
+        new BuildBundle().run(args);
+    }
+
+    /**
+     * Main entry point for both command line driver and
+     * library hook. Consider the help message invoked with
+     * -h for a more complete description of the functionality.
+     *
+     * @param args program arguments.
+     */
+    public static void run(String[] args) {
+
+        String privateKey = null;
+        String version = "1";
+        String requiredHash = "NONE";
+        String outputName = "update_bundle.zip";
+        String otherMeta = null;
+        ArrayList<String> configPaths = new ArrayList<String>();
+        Encoding encodingFunction = Encoding.encodeFunctions.get("base64");
+
+        try {
+            for (int i = 0; i < args.length; i++) {
+                String arg = args[i];
+
+                if (arg.equals("-k")) {
+                    privateKey = args[++i];
+                } else if (arg.equals("-v")) {
+                    version = args[++i];
+                } else if (arg.equals("-r")) {
+                    requiredHash = args[++i];
+                } else if (arg.equals("-o")) {
+                    outputName = args[++i];
+                } else if (arg.equals("-m")) {
+                    otherMeta = args[++i];
+                } else if (arg.equals("-e")) {
+                    encodingFunction = Encoding.encodeFunctions.get(args[++i]);
+                } else if (arg.equals("-h")) {
+                    usage("Tool to build OTA config bundles");
+                } else {
+                    // All positional arguments are files to bundle.
+                    configPaths.add(args[i]);
+                }
+            }
+        } catch (ArrayIndexOutOfBoundsException ex) {
+            usage("Missing required argument.");
+        }
+
+        if (privateKey == null) {
+            usage("No private key specified.");
+        }
+
+        int numOfFiles = configPaths.size();
+        if (numOfFiles == 0) {
+            usage("Must specify at least one config file to bundle.");
+        }
+
+        try {
+            String versionRegex = "\\d+";
+            if (!version.matches(versionRegex)) {
+                throw new IllegalArgumentException("Illegal version: " + version);
+            }
+
+            String hashRegex = "[a-fA-F0-9]{128}";
+            if (!"NONE".equals(requiredHash) && !requiredHash.matches(hashRegex)) {
+                throw new IllegalArgumentException("Illegal SHA-512 hash: " + requiredHash);
+            }
+
+            // Check that the extra meta value is a non-negative integer?
+            String metaRegex = "\\d+";
+            if (otherMeta != null && !otherMeta.matches(metaRegex)) {
+                throw new IllegalArgumentException("Illegal metavalue: " + otherMeta);
+            }
+
+            byte[] bundle = build_bundle(configPaths, encodingFunction);
+            byte[] signed = sign_bundle(bundle, version, privateKey, requiredHash, otherMeta);
+
+            String joined = Joiner.on(":").join(requiredHash, new String(signed), version);
+            if (otherMeta != null) {
+                joined += ":" + otherMeta;
+            }
+            byte[] joined_bytes = joined.getBytes();
+
+            // Build zip file
+            final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputName));
+            ZipEntry e = new ZipEntry("update_bundle");
+            out.putNextEntry(e);
+            out.write(bundle, 0, bundle.length);
+            out.closeEntry();
+            e = new ZipEntry("update_bundle_metadata");
+            out.putNextEntry(e);
+            out.write(joined_bytes, 0, joined_bytes.length);
+            out.closeEntry();
+            out.close();
+        } catch (IOException ioex) {
+            System.out.println("IOException error: " + ioex.toString() + ". Exiting.");
+        } catch (GeneralSecurityException gex) {
+            System.out.println("Security Exception error: " + gex.toString() + ". Exiting.");
+        } catch (IllegalArgumentException iax) {
+            System.out.println(iax.toString());
+        }
+    }
+}

tools/build_bundle/src/com/android/buildbundle/Encoding.java

+package com.android.buildbundle;
+
+import android.util.Base64;
+
+import com.google.common.io.Files;
+
+import java.io.File;
+import java.io.IOException;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Abstract class representing the encoding scheme used
+ * to create an update bundle for loading.
+ */
+abstract class Encoding {
+
+    static final int initialCapacity = 2;
+    public static final Map<String, Encoding> encodeFunctions =
+        new HashMap<String, Encoding>(initialCapacity);
+
+    static {
+        encodeFunctions.put("base64", new Base64Encoding());
+        encodeFunctions.put("none", new NoEncoding());
+    }
+
+    /**
+     * Given a File object encode it according to a
+     * given bundle scheme capable of being loaded
+     * by the ConfigUpdate mechanism.
+     *
+     * @param path File object of the file to encode.
+     *
+     * @exception IOException produced by failed or interrupted
+     *            I/O operations on the requested path or if
+     *            the passed path is null.
+     *
+     * @return byte array of the encoded file scheme.
+     */
+    protected abstract byte[] create_encoding(File path) throws IOException;
+}
+
+/**
+ * Base64 encoding scheme.
+ */
+class Base64Encoding extends Encoding {
+
+    /**
+     * Given a File object encode it as base64 chunked, line
+     * wrapped at 76 characters, with each line ending
+     * in '\n'. A byte array of the encoded file is returned.
+     *
+     * @param path File object of the file to encode.
+     *
+     * @exception IOException produced by failed or interrupted
+     *            I/O operations on the requested path or if
+     *            the passed path is null.
+     *
+     * @return byte array of the encoded file scheme.
+     */
+    @Override
+    protected byte[] create_encoding(File path) throws IOException  {
+        if (path == null) {
+            throw new IOException("Requested path is null.");
+        }
+
+        byte[] policy = Files.toByteArray(path);
+        return Base64.encode(policy, Base64.DEFAULT);
+    }
+}
+
+/**
+ * No encoding scheme implementation.
+ */
+class NoEncoding extends Encoding {
+
+    /**
+     * Given a File object simply return it as a byte array.
+     *
+     * @param path File object of the file to encode.
+     *
+     * @exception IOException produced by failed or interrupted
+     *            I/O operations on the requested path or if
+     *            the passed path is null.
+     *
+     * @return byte array of the encoded file scheme.
+     */
+    @Override
+    protected byte[] create_encoding(File path) throws IOException  {
+        if (path == null) {
+            throw new IOException("Requested path is null.");
+        }
+
+        return  Files.toByteArray(path);
+    }
+}

tools/setool/Android.mk

+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_JAVA_RESOURCE_DIRS := src
+
+LOCAL_JAR_MANIFEST := manifest.txt
+
+LOCAL_MODULE := setool
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_PREBUILT_EXECUTABLES := setool
+
+include $(BUILD_HOST_PREBUILT)

tools/setool/manifest.txt

+Main-Class: com.seandroid.tools.Main
+

tools/setool/setool

+#!/bin/sh
+
+prog="$0"
+progdir=`dirname "${prog}"`
+
+jarfile=setool.jar
+frameworkdir="$progdir"
+
+if [ ! -r "$frameworkdir/$jarfile" ]; then
+    frameworkdir=`dirname "$progdir"`/framework
+fi
+if [ ! -r "$frameworkdir/$jarfile" ]; then
+    root="${ANDROID_BUILD_TOP}"
+    if [ -z $root ]; then
+        echo "ANDROID_BUILD_TOP var not found. Trying running 'lunch' command first."
+        exit 1
+    fi
+    root=$root"/out/host"
+    spot="."
+    uname=`uname -a`
+    mac=$(echo $uname | grep "Darwin")
+    if [ -n mac ]; then
+        mac_type=$(echo $uname | grep -e "i386" -e "x86_64")
+        if [ -n mac_type ]; then
+            spot="darwin-x86"
+        else
+            spot="darwin-ppc"
+        fi
+    fi
+    linux=$(echo $uname | grep "Linux")
+    if [ -n linux ]; then
+        spot="linux-x86"
+    fi
+    frameworkdir="$root"/"$spot"/framework
+fi
+if [ ! -r "$frameworkdir/$jarfile" ]; then
+    echo `basename "$prog"`": can't find $jarfile"
+    echo "Make sure setool.jar has been built."
+    exit 1
+fi
+
+jarpath="$frameworkdir/$jarfile"
+
+exec java -Xmx128M -jar "$jarpath" "$@"

tools/setool/src/com/seandroid/tools/Main.java

+package com.seandroid.tools;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class Main {
+
+    private static final String DOT_APK = ".apk";
+
+    private static final int EXIT_ERROR   = 1;
+    private static final int EXIT_SUCCESS = 0;
+
+    static boolean mVerbose  = false;
+    private static boolean mPolicy   = false;
+    private static boolean mBuildPolicy = false;
+
+    private static PrintStream mOutput = System.out;
+    static PrintStream ERROR = System.out;
+    private static String mApkDirectory = ".";
+
+    private static String mBuildType = Usage.KEYS_TAG;
+    private static String mPolicyFile;
+    private static String mSeinfo;
+
+    private static Set<String> mApks = new HashSet<String>(5);
+
+    public Main() {
+    }
+
+    public static void main(String args[]) {
+        new Main().run(args);
+    }
+
+    private static String getArg(String[] args, int index) {
+        try {
+            return args[index];
+        } catch (ArrayIndexOutOfBoundsException e) {
+            ERROR.println("Option " + args[index - 1] + " without a string.\n");
+            Usage.printUsage(System.out);
+            System.exit(EXIT_ERROR);
+        }
+        return null;
+    }
+
+    private void run(String[] args) {
+        if (args.length < 1) {
+            Usage.printUsage(System.err);
+            System.exit(EXIT_ERROR);
+        }
+
+        for (int index = 0; index < args.length; index++) {
+            String arg = args[index];
+
+            if (Usage.HELP.equals(arg)) {
+                Usage.printUsage(System.out);
+                System.exit(EXIT_SUCCESS);
+            } else if (Usage.BUILD.equals(arg)) {
+                mBuildType = getArg(args, ++index);
+                mBuildPolicy = true;
+            } else if (Usage.APKDIR.equals(arg)) {
+                mApkDirectory = getArg(args, ++index);
+            } else if (Usage.SEINFO.equals(arg)) {
+                mSeinfo = getArg(args, ++index);
+            } else if (Usage.POLICYFILE.equals(arg)) {
+                mPolicyFile = getArg(args, ++index);
+                mPolicy = true;
+            } else if (Usage.VERBOSE.equals(arg)) {
+                mVerbose = true;
+            } else if (Usage.OUTFILE.equals(arg)) {
+                File out = new File(getArg(args, ++index));
+                if (out.exists() && !out.canWrite()) {
+                    ERROR.println(out.getPath() + ": Not writable. " +
+                                       "Writing to stdout instead.");
+                    continue;
+                }
+                try {
+                    mOutput = new PrintStream(out);
+                } catch (FileNotFoundException e) {
+                    ERROR.println("Defaulting to stdout." + e.toString());
+                }
+            } else if (arg.startsWith("-")) {
+                ERROR.println("Invalid argument " + arg + ".\n");
+                Usage.printUsage(System.err);
+                System.exit(EXIT_ERROR);
+            } else {
+                // Any piece not prefixed with '-' is considered an apk.
+                // Make sure it sorta looks like an apk
+                if (arg.endsWith(DOT_APK)) {
+                    mApks.add(arg);
+                } else {
+                    ERROR.println(arg + ": Skipping. Doesn't end with '" + DOT_APK + "'\n");
+                }
+            }
+        }
+
+        // mutually exclusive options
+        if (mPolicy && mBuildPolicy) {
+            ERROR.println("Can only specify one of " + Usage.BUILD +
+                          " or " + Usage.POLICYFILE);
+            Usage.printUsage(System.err);
+            System.exit(EXIT_ERROR);
+        }
+
+        // if building a stanza then an seinfo tag is required
+        if (mBuildPolicy && mSeinfo == null) {
+            ERROR.println("Must specify an seinfo label. Exiting");
+            Usage.printUsage(System.err);
+            System.exit(EXIT_ERROR);
+        }
+
+        // we need at least 1 apk to work with
+        if (mApks.size() == 0) {
+            ERROR.println("No apks to analyze. Exiting.");
+            System.exit(EXIT_ERROR);
+        }
+
+        if (mBuildPolicy) {
+            Set<String> derivedPolicies = new HashSet<String>();
+
+            for (String apk : mApks) {
+                File apk_file = new File(apk);
+                if (!apk_file.isAbsolute()) {
+                    File file = new File(mApkDirectory, apk);
+                    if (!file.exists()) {
+                        ERROR.println(file.getPath() + " doesn't exist. Skipping.");
+                        continue;
+                    }
+                    apk = file.getPath();
+                }
+                Package app = new Package(mOutput);
+                if (mBuildType.equals(Usage.PACKAGE)) {
+                    derivedPolicies.add(app.createPolicyEntry(apk, mSeinfo));
+                } else if (mBuildType.equals(Usage.KEYS_TAG)) {
+                    derivedPolicies.add(app.createKeysOnly(apk, mSeinfo));
+                } else {
+                    ERROR.println("Didn't specify a valid " + Usage.BUILD + " option.");
+                    Usage.printUsage(System.out);
+                    System.exit(EXIT_ERROR);
+                }
+            }
+            // Dump all policies created.
+            for (String policy : derivedPolicies) {
+                mOutput.println(policy);
+            }
+        } else if (mPolicy) {
+            try {
+                if (mVerbose) {
+                    ERROR.println("Parsing policy file " + mPolicyFile);
+                }
+                PolicyParser.PolicyStart(new File(mPolicyFile));
+            } catch (Exception e) {
+                ERROR.println("Error parsing policy file " + mPolicyFile + ".\n" + e.toString());
+                System.exit(EXIT_ERROR);
+            }
+            for (String apk : mApks) {
+                File apk_file = new File(apk);
+                if (!apk_file.isAbsolute()) {
+                    File file = new File(mApkDirectory, apk);
+                    if (!file.exists()) {
+                        ERROR.println(file.getPath() + " doesn't exist. Skipping.");
+                        continue;
+                    }
+                    apk = file.getPath();
+                }
+                if (mVerbose) {
+                    ERROR.println("Checking app for cert(s) and package name.");
+                }
+                Package app = new Package(mOutput);
+                app.readCerts(apk);
+                app.aapt(apk);
+                Set<String> sigs = app.getCerts();
+                String name = app.getPackageName();
+                if (mVerbose) {
+                    ERROR.println("Checking policy for " + apk + " against " + mPolicyFile);
+                }
+                String seinfo = PolicyParser.passedPolicy(sigs, name);
+                if (seinfo == null) {
+                    mOutput.println("seinfo tag null assigned to " + apk + ".\n");
+                } else {
+                    mOutput.println("seinfo tag " + seinfo + " assigned to " + apk + ".\n");
+                }
+            }
+        } else {
+            ERROR.println("Didn't specify a proper policy option.");
+            Usage.printUsage(System.out);
+            System.exit(EXIT_ERROR);
+        }
+    }
+}

tools/setool/src/com/seandroid/tools/Package.java

+package com.seandroid.tools;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Set;
+
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+
+public class Package {
+
+    private String mPackageName;
+    private String mPolicyXml;
+    private final PrintStream mWriter;
+
+    private final Set<String> mX509Certs = new HashSet<String>(2);
+
+    private static final String AAPT_CMD = "aapt d permissions";
+    private static final String AAPT_PACKAGE = "package:";
+
+    private static final String ANDROID_MANIFEST_FILE = "AndroidManifest.xml";
+
+    public Package(PrintStream output) {
+        mWriter = output;
+    }
+
+    public String createPolicyEntry(String apk, String seinfo) {
+        if (Main.mVerbose) {
+            Main.ERROR.println("Checking " + apk + " for cert(s) and package name.");
+        }
+        readCerts(apk);
+        aapt(apk);
+        return PolicyBuilder.createStanza(mX509Certs, mPackageName, seinfo);
+    }
+
+    public String createKeysOnly(String apk, String seinfo) {
+        readCerts(apk);
+        return PolicyBuilder.createSignerOnlyStanza(mX509Certs, seinfo);
+    }
+
+
+    public void aapt(String apk) {
+
+        String path = System.getenv("ANDROID_HOST_OUT");
+        String CMD = AAPT_CMD;
+        if (path == null) {
+            Main.ERROR.println("Warning. Might not find 'aapt' tool." +
+                               " Try running 'lunch' command first.");
+        } else {
+            final String separator = System.getProperty("file.separator");
+            CMD = path + separator + "bin" + separator + AAPT_CMD;
+        }
+
+        try {
+            Process proc = Runtime.getRuntime().exec(CMD + " " + apk);
+
+            InputStreamReader isr =
+                new InputStreamReader(proc.getInputStream());
+
+            BufferedReader in = new BufferedReader(isr);
+            String line = null;
+            while ((line = in.readLine()) != null) {
+                if (line.startsWith(AAPT_PACKAGE)) {
+                    mPackageName = line.substring(AAPT_PACKAGE.length() + 1);
+                if (Main.mVerbose) {
+                    Main.ERROR.println("Found package name for app : " + mPackageName);
+                }
+                }
+            }
+
+        } catch (IOException e) {
+            Main.ERROR.println("Had trouble with 'aapt' process. Results for " +
+                               apk + " questionable: " + e.toString());
+        }
+    }
+
+    public void readCerts(String apk) {
+        try {
+            JarFile jarFile = new JarFile(apk);
+            JarEntry jarEntry = jarFile.getJarEntry(ANDROID_MANIFEST_FILE);
+
+            byte[] readBuffer = new byte[8192];
+
+            InputStream is =
+                new BufferedInputStream(jarFile.getInputStream(jarEntry));
+
+            while (is.read(readBuffer, 0, readBuffer.length) != -1) {
+                ; // we only read to get to the cert
+            }
+            is.close();
+
+            Certificate[] certs = jarEntry.getCertificates();
+            if (certs == null) {
+                Main.ERROR.println("No certs found for " + apk);
+                return;
+            }
+
+            for (Certificate cert : certs) {
+                byte sigs[] = cert.getEncoded();
+                int N = sigs.length;
+                final int N2 = N*2;
+                char[] text = new char[N2];
+                for (int j=0; j<N; j++) {
+                    byte v = sigs[j];
+                    int d = (v >> 4) & 0xf;
+                    text[j*2] = (char)(d >= 10 ? ('a' + d-10) : ('0' + d));
+                    d = v & 0xf;
+                    text[j*2 + 1] = (char)(d >= 10 ? ('a' + d-10) : ('0' + d));
+                }
+                mX509Certs.add(new String(text));
+                if (Main.mVerbose) {
+                    Main.ERROR.println("Found cert for app : " + new String(text));
+                }
+            }
+            jarFile.close();
+        } catch (IOException e) {
+            Main.ERROR.println("Had trouble extracting certs. Results for " +
+                               apk + " questionable: " + e.toString());
+        } catch (CertificateEncodingException e) {
+            Main.ERROR.println("Had trouble extracting certs. Results for " +
+                               apk + " questionable: " + e.toString());
+        }
+    }
+
+    public Set<String> getCerts() {
+        return mX509Certs;
+    }
+
+    public String getPackageName() {
+        return mPackageName;
+    }
+
+    private void dumpPolicy() {
+        mWriter.println(mPolicyXml);
+    }
+}

tools/setool/src/com/seandroid/tools/PolicyBuilder.java

+package com.seandroid.tools;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.TreeSet;
+
+public class PolicyBuilder {
+
+    static final String POLICY           = "policy";
+    static final String NAME_ATTR        = "name";
+    static final String PACKAGE          = "package";
+    static final String DEFAULT          = "default";
+    static final String SEINFO           = "seinfo";
+    static final String SIGNER           = "signer";
+    static final String SIGNATURE_ATTR   = "signature";
+    static final String VALUE_ATTR       = "value";
+
+    private static final String XML_END_TAG_ATTRIBUTE = "\">\n";
+    private static final String XML_NO_CHILD_END_TAG_ATTR = "\" />\n";
+    private static final String INDENT_ONE = "  ";
+    private static final String INDENT_TWO = "    ";
+
+    private static final String SIGNER_TAG_START;
+    private static final String SIGNER_TAG_END;
+    private static final String PACKAGE_TAG_START;
+    private static final String PACKAGE_TAG_END;
+    private static final String SEINFO_TAG_START;
+
+    static {
+        SIGNER_TAG_START = "<" + SIGNER + " " + SIGNATURE_ATTR + "=\"";
+
+        SIGNER_TAG_END = "</" + SIGNER + ">\n";
+
+        PACKAGE_TAG_START = "<" + PACKAGE + " " + NAME_ATTR + "=\"";
+
+        PACKAGE_TAG_END = "</" + PACKAGE + ">\n";
+
+        SEINFO_TAG_START = "<" + SEINFO + " " + VALUE_ATTR + "=\"";
+    }
+
+    private static final String signerTag(String x509) {
+        StringBuilder str = new StringBuilder(SIGNER_TAG_START);
+        str.append(x509);
+        str.append(XML_END_TAG_ATTRIBUTE);
+        return str.toString();
+    }
+
+    private static final String seinfoTag(String value) {
+        StringBuilder str = new StringBuilder(SEINFO_TAG_START);
+        str.append(value);
+        str.append(XML_NO_CHILD_END_TAG_ATTR);
+        return str.toString();
+    }
+
+    private static final String packageTag(String name) {
+        StringBuilder str = new StringBuilder(PACKAGE_TAG_START);
+        str.append(name);
+        str.append(XML_END_TAG_ATTRIBUTE);
+        return str.toString();
+    }
+
+    public static final String createSignerOnlyStanza(Set<String> x509, String seinfo) {
+        StringBuilder ret = new StringBuilder();
+        for (String sig : x509) {
+            ret.append(signerTag(sig));
+            ret.append(INDENT_ONE + seinfoTag(seinfo));
+            ret.append(SIGNER_TAG_END);
+        }
+        return ret.toString();
+    }
+
+    public static final String createStanza(Set<String> x509, String name, String seinfo) {
+        StringBuilder ret = new StringBuilder();
+        for (String sig : x509) {
+            ret.append(signerTag(sig));
+            ret.append(INDENT_ONE + packageTag(name));
+            ret.append(INDENT_TWO + seinfoTag(seinfo));
+            ret.append(INDENT_ONE + PACKAGE_TAG_END);
+            ret.append(SIGNER_TAG_END);
+        }
+        return ret.toString();
+    }
+}

tools/setool/src/com/seandroid/tools/PolicyParser.java

+package com.seandroid.tools;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class PolicyParser {
+
+    // All signature based policy stanzas
+    private static HashMap<String, Policy> sSigSeinfo = new HashMap<String, Policy>();
+
+    // Default seinfo tag
+    private static String sDefaultSeinfo = null;
+
+    // Policy for signer stanzas
+    static class Policy {
+        private String seinfo;
+        private final HashMap<String, String> pkgMap;
+
+        Policy() {
+            seinfo = null;
+            pkgMap = new HashMap<String, String>();
+        }
+
+        void putSeinfo(String seinfoValue) {
+            seinfo = seinfoValue;
+        }
+
+        void putPkg(String pkg, String seinfoValue) {
+            pkgMap.put(pkg, seinfoValue);
+        }
+
+        boolean isValid() {
+            return (seinfo != null) || (!pkgMap.isEmpty());
+        }
+
+        String checkPolicy(String pkgName) {
+            String seinfoValue = pkgMap.get(pkgName);
+            if (seinfoValue != null) {
+                return seinfoValue;
+            }
+            return seinfo;
+        }
+
+        String print() {
+            StringBuilder sb = new StringBuilder();
+            sb.append("\nglobal seinfo = " + seinfo + "\n");
+            for (Map.Entry<String, String> entry : pkgMap.entrySet()) {
+                String key = entry.getKey();
+                Object value = entry.getValue();
+                sb.append("inner package (" + key + ") with seinfo = " + value + "\n");
+            }
+            return sb.toString();
+        }
+    }
+
+    /**
+     * Parses a mac_permissions.xml file and determines its internal policy
+     * structure. All errors are treated as exceptions and are thrown
+     * as Exception class.
+     */
+    public static void PolicyStart(File policyFile) throws Exception {
+
+        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
+        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
+        Document doc = dBuilder.parse(policyFile);
+
+        NodeList nList = doc.getElementsByTagName(PolicyBuilder.POLICY);
+        if (nList == null)
+            throw new Exception("No " + PolicyBuilder.POLICY + " root tag found.");
+
+        if (nList.getLength() > 1)
+            Main.ERROR.println("Multiple " + PolicyBuilder.POLICY + " tags " +
+                                 "found. Using the first to determine policy.");
+
+        Node nNode = nList.item(0);
+        if (nNode == null)
+            throw new Exception("No " + PolicyBuilder.POLICY + " root tag found.");
+
+        NodeList policyChildren = nNode.getChildNodes();
+        for (int i = 0; i < policyChildren.getLength(); ++i) {
+            Node nNoded = policyChildren.item(i);
+            if (nNoded.getNodeType() == Node.ELEMENT_NODE) {
+                Element f = (Element)nNoded;
+                String tagName = f.getTagName();
+                if (PolicyBuilder.SIGNER.equals(tagName)) {
+                    String signer = f.getAttribute(PolicyBuilder.SIGNATURE_ATTR);
+                    if (signer == null) {
+                        if (Main.mVerbose) {
+                            Main.ERROR.println("Bad signature found in policy file " + policyFile +
+                                               " : " + signer + ". Skipping stanza.");
+                        }
+                        continue;
+                    }
+                    Policy policy = readPolicyTags(nNoded);
+                    if (policy.isValid()) {
+                        if (Main.mVerbose) {
+                            Main.ERROR.println("Found signer tag (" + signer +
+                                               ") with " + policy.print());
+                        }
+                        sSigSeinfo.put(signer, policy);
+                    }
+                } else if (PolicyBuilder.DEFAULT.equals(tagName)) {
+                    sDefaultSeinfo = readSeinfoTag(nNoded);
+                    if (Main.mVerbose) {
+                        Main.ERROR.println("<default> has seinfo = " + sDefaultSeinfo + "\n");
+                    }
+                }
+            }
+        }
+    }
+
+    private static Policy readPolicyTags(Node node) {
+        NodeList policyChildren = node.getChildNodes();
+        Policy policy = new Policy();
+        for (int i = 0; i < policyChildren.getLength(); ++i) {
+            Node nNoded = policyChildren.item(i);
+            if (nNoded.getNodeType() == Node.ELEMENT_NODE) {
+                Element f = (Element)nNoded;
+                String tagName = f.getTagName();
+                if (PolicyBuilder.SEINFO.equals(tagName)) {
+                    String seinfo = f.getAttribute(PolicyBuilder.VALUE_ATTR);
+                    if (validateValue(seinfo)) {
+                        policy.putSeinfo(seinfo);
+                    }
+                } else if (PolicyBuilder.PACKAGE.equals(tagName)) {
+                    String pkg = f.getAttribute(PolicyBuilder.NAME_ATTR);
+                    if (pkg == null) {
+                        continue;
+                    }
+                    String seinfo = readSeinfoTag(nNoded);
+                    if (validateValue(seinfo)) {
+                        policy.putPkg(pkg, seinfo);
+                    }
+                }
+            }
+        }
+        return policy;
+    }
+
+    private static String readSeinfoTag(Node node) {
+        String seinfo = null;
+        NodeList policyChildren = node.getChildNodes();
+        for (int i = 0; i < policyChildren.getLength(); ++i) {
+            Node nNoded = policyChildren.item(i);
+            if (nNoded.getNodeType() == Node.ELEMENT_NODE) {
+                Element f = (Element)nNoded;
+                String tagName = f.getTagName();
+                if (PolicyBuilder.SEINFO.equals(tagName)) {
+                    String se = f.getAttribute(PolicyBuilder.VALUE_ATTR);
+                    if (validateValue(se)) {
+                        seinfo = se;
+                    }
+                }
+            }
+        }
+
+        return seinfo;
+    }
+
+    private static boolean validateValue(String name) {
+        if (name == null)
<