2013年5月26日 星期日

SELinux MAC Policy Files


The MAC policy configuration files are contained in the external/sepolicy directory, however there may also be policy configuration files to enable specific device features under device/<vendor> directories (see the Building the Policy section). Once generated, the policy and its supporting configuration files are installed on the device as part of the build process.


The following files are used to build the kernel binary policy file that will be named sepolicy and installed by default in the root directory. An updated policy may be installed at /data/security/sepolicy. The initialisation or policy reload process will always check for a policy at /data/security/sepolicy first and then if not present at /sepolicy. The policy files consist of the following:

access_vectors, security_classes

These have been modified to support the new SE for Android classes and permissions.
Access decisions specify whether or not a permission is granted for a given pair of SIDs and class. Each object class has a set of associated permissions defined to control operations on objects with that class. These permission sets are represented by a bitmap called an access vector. The corresponding constants for permissions are defined in the automatically generated header file av_permissions.h (external/libsepol/src and kernel/goldfish/security/selinux). This file looks like below figure:
Above table is generated by "kernel/goldfish/scripts/selinux/genheaders.c" according to "kernel/goldfish/security/selinux/include/classmap.h". Below figure shows the contents of classmap.h.

access_vectors is used in external/libsepol/include/sepol/policydb/flask_types.h. It defines the access vector permissions for each class.
Below is an example of access_vectors file
# Define common prefixes for access vectors
#
# common common_name { permission_name ... }

#
# Define a common prefix for file access vectors.
#

common file
{
ioctl
read
write
create
getattr
setattr
lock
relabelfrom
relabelto
append
unlink
link
rename
execute
swapon
quotaon
mounton
}

#
# Define the access vectors.
#
# class class_name [ inherits common_name ] { permission_name ... }
#
# Define the access vector interpretation for file-related objects.
#

class filesystem
{
mount
remount
unmount
getattr
relabelfrom
relabelto
transition
associate
quotamod
quotaget
}

security_classes is used in external/libsepol/include/sepol/policydb/flask_types.h. It declares the security classes.
Below is an example of security_classes file
#Classes marked as userspace are classes
#for userspace object managers

class security
class process
class system
class capability

#file-related classes
class filesystem
class file
class dir

#network-related classes
class socket
class tcp_socket
class udp_socket

The relation between access_vectors and security_classes is as below figure:



initial_sids, initial_sid_contexts, fs_use, genfs_contexts, port_contexts 
For flexibility of policy building, these files have been separated to allow additional policy files to be defined for specific devices.
initial_sids is used in external/libselinux/src/avc.c and external/libselinux/src/get_initial_context.c. It Declares initial SIDs. Such as:
sid kernel 
sid security
sid fs 
sid file 
initial_sid_contexts declares initial SID contexts. Such as:
sid kernel u:r:kernel:s0
sid security u:object_r:kernel:s0
sid fs u:object_r:labeledfs:s0
sid file u:object_r:unlabeled:s0
The relation of init_sids and init_sid_contexts is as below figure:


fs_use is used in external/libsepol/include/sepol/policydb/service.h & kernel/goldfish/security/selinux/ss/services.c, ... files.
fs_use_xattr yaff2 u:object_r:labeledfs:s0;
fs_use_xattr ext2 u:object_r:labeledfs:s0;
fs_use_trans tmpfs u:object_r:tmpfs:s0;
fs_use_trans mqueue u:object_r:mqueue:s0
genfs_contexts is used in kernel/goldfish/security/selinux/hooks.c
genfscon rootfs / u:object_r:rootfs:s0
# sysfs labels can be set by userspace
genfscon sysfs / u:object_r:sysfs:s0
genfscon vfat / u:object_r:sdcard:s0


port_contexts defines the socket port contexts. It is used in external/libsepol/src/polcaps.c and kernel/goldfish/security/selinux/selinuxfs.c
# portcon statements 
portcon tcp 80 u:object_r:http_port:s0

users, roles
These define the only user (u) and role (r) used by the policy, although there is no reason why others cannot be added.
users file:
user u roles { r } level s0 range s0 - mls_systemhigh;
roles file:
role r; 
role r types domain;


 mls
Contains the constraints applied to the defined classes and permissions.

global_macros, mls_macro, te_marcos
These contain the m4 macros that expand the policy files to build a policy in the kernel policy language as described in the Policy Language section. The policy can then be compiled by checkpolicy(8). For reference, the policy text file is built and placed in: out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf The compiled kernel policy can also be found in this directory and is named sepolicy. There are also policy.conf.dontaudit andsepolicy.dontaudit files that have the dontaudit rules removed. Stripping out these rules stops the auditing of denial messages as they are known events and do not cause any issues. This also helps to manage the audit log by excluding known denial events.

attributes 
Contains the attribute names (forming the attribute statements) that will be used to group type identifiers defined by the policy. Types are the basic building blocks for TE rules. SELinux primarily uses types to determine what access is allowed. Attributes and aliases are policy features that ease the management and use of types. We use attributes to refer to a group of types with a single identifier.
The statement definition is:
attribute attribute_id;
Where:
attributeThe attribute keyword.
attribute_idThe attribute identifier.

Type statement syntax:
type type_id [alias alias_id] [,attribute_id];

attributes declarations:
#All types used for devices.
attribute dev_type;

#All types used for processes
attribute domain;

#All types used for domain entry points
attribute exec_type;



policy_capabilities
Contains the policy capabilities enabled for the kernel policy (see policycap statement). It is used in external/libsepol/src/polcaps.c and kernel/goldfish/security/selinux/selinuxfs.c.
The statement definition is:
policycap capability;
Where:
policycapThe policycap keyword.
capabilityThe capability identifier that needs to be enabled for this policy.
# This statement enables the network_peer_controls to be enabled
# for use by the policy. 
# 

policycap network_peer_controls;

*.te
The *.te files are the policy module definition files. These are the same format as the standard reference policy and are expanded by the m4 macros. There is (generally) one .te file for each domain/service defined for the device and will contain all the required allow, type_transition etc. rules. It will also call any te_macros to access other domains resources (e.g. init_daemon_domain, binder_call).


The following files are used to compute and/or configure SE for Android security contexts and reflect information configured within the kernel policy. These files are:

  file_contexts 
Contains default file contexts for setting the filesystem as standard SELinux. The format of this file is defined in file_contexts(5). The file is installed by default in the root directory. SE for Android services (such as restorecon(8)) will first check for this file at (this is where updated files should be placed):
  /data/security/file_contexts
 If not present they will then check the root directory:
  /file_contexts
Example file_contexts contents:
#root
/                  u:object_r:rootfs:s0

#Data File
/adb_keys          u:object_r:rootfs:s0
/defcult.prop      u:object_r:rootfs:s0

#Executables       
/init              u:object_r:rootfs:s0
/sbin(/.*)?        u:object_r:rootfs:s0

#Devices
/dev(/.*)?         u:object_r:device:s0
/dev/alarm         u:object_r:alarm_device:s0
/dev/audio.*       u:object_r:audio_device:s0

Below figures show the file_contexts you will see in the console.


  property_contexts
Contains default contexts to be applied to Android property services as discussed in the property_contexts file section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files should be placed):
  /data/security/property_contexts
 If not present they will then check the root directory:
  /property_contexts
This file is used in system/core/init/initc.
Example of property_contexts
##########################
# property service keys
#
 
net.rmnet0              u:object_r:radio_prop:s0
net.gprs                u:object_r:radio_prop:s0
net.ppp                 u:object_r:radio_prop:s0
net.qmi                 u:object_r:radio_prop:s0
net.lte                 u:object_r:radio_prop:s0
net.cdma                u:object_r:radio_prop:s0
gsm.                    u:object_r:radio_prop:s0
persist.radio           u:object_r:radio_prop:s0
net.dns                 u:object_r:radio_prop:s0
sys.                    u:object_r:system_prop:s0
service.                u:object_r:system_prop:s0
wlan.                   u:object_r:system_prop:s0
dhcp.                   u:object_r:system_prop:s0
debug.                  u:object_r:shell_prop:s0
log.                    u:object_r:shell_prop:s0

system/core/init/property_service.c will set property services


  seapp_contexts 
Contains information to allow domain or file contexts to be computed based on parameters as discussed in the seapp_contexts file section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files should be placed):
  /data/security/seapp_contexts
 If not present they will then check the root directory:
  /seapp_contexts
This file is used in external/sepolicy/check_seapp/check_seapp.c and external/libselinux/src/android.c
isSystemServer=true domain=system
user=system domain=system_app type=system_data_file
user=bluetooth domain=bluetooth type=bluetooth_data_file
user=nfc domain=nfc type=nfc_data_file
user=radio domain=radio type=radio_data_file
user=_app domain=untrusted_app type=app_data_file levelFrom=app
user=_app seinfo=platform domain=platform_app type=platform_app_data_file
user=_app seinfo=shared domain=shared_app type=platform_app_data_file
user=_app seinfo=media domain=media_app type=platform_app_data_file
user=_app seinfo=release domain=release_app type=platform_app_data_file
user=_isolated domain=isolated_app


Above picture shows "untrusted_app" domain defined in seapp_contexts and the process contexts shown in system.
If the "untrusted_app" domain is not defined in seapp_coontexts, the process context will become "zygote", a default label. The picture is shown as below.


  selinux-network.sh 
If using iptables(8) then SECMARK information may be configured in this file as part of the build. It is installed in system/bin and executed at system initialisation time.


Reference: 

2013年5月24日 星期五

SEforAndroid

Policy

1. Policy sources are located at "external/sepolicy". There may also be policy configuration files to enable specific device features under device/<vendor>/<device>/sepolicy directories

2. The policy consists of source files used to generate the SELinux kernel policy file, a file_contexts configuration, a property_contexts configuration, a seapp_contexts configuration, and a mac_permissions.xml configuration.
  • The file_contexts configuration is used to label files at build time (e.g. the system partition) and at runtime (e.g. device nodes, service socket files, /data directories created by init.rc, ...). The file_contexts configuration content of AOSP and SEforAndroid are a little different. It will be used by external/libselinux/src/android.c and external/libsepol/src/module.c.
  • The property_contexts configuration is used to specify the security context of Android properties for permission checking purposes.  The property_contexts configuration content of AOSP and SEforAndroid are a little different. It will be used by system/core/init/init.c and frameworks/base/services/java/com/android/server/DevicePolicyManagerService.java.
  • The seapp_contexts configuration is used to label app processes and app package directories. The seapp_contexts configuration content of AOSP and SEforAndroid are a little different. It is used by external/libselinux/src/android.c and frameworks/base/services/java/com/android/server/DevicePolicyManagerService.java.
  • The mac_permissions.xml configuration is the middleware MAC policy. The mac_permissions.xml configuration content of AOSP and SEforAndroid are a little different. It is used by frameworks/base/services/java/com/android/server/DevicePolicyManagerService.java, external/sepolicy/tools/setool/src/com/seandroid/tools/PolicyParser.java, frameworks/base/services/java/com/android/server/pm/SELinuxMMAC.java and some *.py files.
  • The property_contexts, seapp_contexts, and mac_permissions.xml configurations are unique to SE for Android (i.e. they were not part of the regular SELinux policy).

3.Device-specific policy can be specified by defining BOARD_SEPOLICY_DIRS, BOARD_SEPOLICY_UNION and/or BOARD_SEPOLICY_REPLACE, BOARD_SEPOLICY_IGNORE variables in a BoardConfig.mk file under the device/<vendor>/<device> or vendor/<vendor>/<device> directories.
  • BOARD_SEPOLICY_UNION is a list of files that will be "unioned", IE concatenated, at the END of their respective file in external/sepolicy. Note, to add a unique file you would use this variable.
  • BOARD_SEPOLICY_REPLACE is a list of files that will be used instead of the corresponding file in external/sepolicy.
  • BOARD_SEPOLICY_DIRS contains a list of directories to search for BOARD_SEPOLICY_UNION and BOARD_SEPOLICY_REPLACE files. Order matters in this list.
  • BOARD_SEPOLICY_IGNORE is a list of paths (directory + filename) of files that are not to be included in the resulting policy. This list is passed to filter-out to remove any paths you may want to ignore. This is useful if you have numerous config directories that contain a file and you want to NOT include a particular file in your resulting policy file, either by UNION or REPLACE.
4. SELinux kernel policy is presently compiled as part of the Android build and added to the ramdisk image so that it can be loaded by init very early in boot, before mounting the system partition.

5.Once the data partition has been mounted, policy can be reloaded from /data/security by placing policy files under /data/security and setting the selinux.reload_policy property to 1 (setprop selinux.reload_policy 1). This will trigger a reload of policy by init, which will also restart ueventd and installd so that they can reload the policy configuration files relevant to their operation.

6.The initialisation or policy reload process will always check for a policy at /data/security/sepolicy first and then if not present at /sepolicy. 

7.The policy can then be compiled by checkpolicy(8). For reference, the policy text file is built and placed in: 
out/target/product/<device>/obj/ETC/sepolicy_intermediates/policy.conf

8. The *.te files are the policy module definition files. These are the same format as the standard reference policy and are expanded by the m4 macros. There is (generally) one .te file for each domain/service defined for the device and will contain all the required allow, type_transition etc. rules. It will also call any te_macros to access other domains resources (e.g. init_daemon_domain, binder_call).

9. seapp_contexts --
 This file is loaded and sorted into memory automatically on first use of one of the following SE for Android libselinux functions that are called by the SE for Android enabled services:
selinux_android_setcontext - Computes process security contexts.selinux_android_setfilecon2 - Computes file/directory security contexts.
selinux_android_seapp_context_reload will also reload this file.

Above functions are implemented in external/libselinux/src/android.c

Input selectors from seapp_contexts file:
  • isSystemServer (boolean)
  • user (string)
  • seinfo (string)
  • name (string) - A package name e.g. com.example.demo
  • sebool (string) - The boolean must be ‘active’ (enabled/true)

isSystemServer=true can only be used once. An unspecified isSystemServer defaults to false.

An unspecified string selector will match any value.

A user string selector that ends in * will perform a prefix match.

user=app_* will match any regular app UID.

user=isolated will match any isolated service UID.

All specified input selectors in an entry must match (i.e. logical AND).

Matching is case-insensitive.

Precedence rules:
1) isSystemServer=true before isSystemServer=false.
2) Specified user= string before unspecified user= string.
3) Fixed user= string before user= prefix (i.e. ending in *).
4) Longer user= prefix before shorter user= prefix.
5) Specified seinfo= string before unspecified seinfo= string.
6) Specified name= string before unspecified name= string.
7) Specified sebool= string before unspecified sebool= string.

Outputs:
domain (string) - The type component of a process context.
type (string) - The type component of a file/directory context.level
From (string; one of none, all, app, or user) - A level that will be automatically computed based on the parameter.
level (string) - A predefined level (e.g. s0:c1022.c1023)

Only entries that specify domain= will be used for app process labeling.

Only entries that specify type= will be used for app directory labeling.

levelFrom=user is only supported for _app or _isolated UIDs.

levelFrom=app or levelFrom=all is only supported for _app UIDs.

level may be used to specify a fixed level for any UID.

10. file_contexts --
Contains default file contexts for setting the filesystem as standard SELinux. The format of this file is defined in file_contexts. The file is installed by default in the root directory. SE for Android services (such as restorecon) will first check for this file at (this is where updated files should be placed): /data/security/file_contexts



This file becomes the policies ./contexts/files/file_contexts file and is built from entries in the ./modules/active/file_contexts.template file as explained above and shown in above picture. It is then used by the file labeling utilities to ensure that files and directories are labeled according to the policy.

Example file_contexts contents:
#root
/                  u:object_r:rootfs:s0

#Data File
/adb_keys          u:object_r:rootfs:s0
/defcult.prop      u:object_r:rootfs:s0

#Executables       
/init              u:object_r:rootfs:s0
/sbin(/.*)?        u:object_r:rootfs:s0

#Devices
/dev(/.*)?         u:object_r:device:s0
/dev/alarm         u:object_r:alarm_device:s0
/dev/audio.*       u:object_r:audio_device:s0

11. property_contexts --
Contains default contexts to be applied to Android property services as discussed in the property_contexts file section. The file is installed by default in the root directory. The SE for Android initialisation / reload process will first check for this file at (this is where updated files should be placed):
/data/security/property_contexts

This file holds property names and their contexts that will be applied by SELinux when applications are loaded. The property names reflect the 'white list' of Android property entries that are also built into the system (see system/core/init/property_service.c and init.c) however there are also additional property entries for applications that require specific contexts to be set.

Each line within the property contexts file is as follows:
property_key context

Where:
property_key The key used to obtain the context that may contain '*' for wildcard matching.
context The security context that will be applied to the object.

Example of property_contexts
##########################
# property service keys
#
 
net.rmnet0              u:object_r:radio_prop:s0
net.gprs                u:object_r:radio_prop:s0
net.ppp                 u:object_r:radio_prop:s0
net.qmi                 u:object_r:radio_prop:s0
net.lte                 u:object_r:radio_prop:s0
net.cdma                u:object_r:radio_prop:s0
gsm.                    u:object_r:radio_prop:s0
persist.radio           u:object_r:radio_prop:s0
net.dns                 u:object_r:radio_prop:s0
sys.                    u:object_r:system_prop:s0
service.                u:object_r:system_prop:s0
wlan.                   u:object_r:system_prop:s0
dhcp.                   u:object_r:system_prop:s0
debug.                  u:object_r:shell_prop:s0
log.                    u:object_r:shell_prop:s0

Build Tools

The kernel policy is compiled using checkpolicy(8) via the external/sepolicy/Android.mk file. There are also a number of SE for Android specific tools used to assist in policy configuration that are described in Policy Build Tools, with a summary as follows:
  • checkfc - Used to parse the file_contexts file against the binary policy sepolicy. This is to ensure all file contexts are valid for the policy. There is a -p option that is used to validate the contexts defined in the property_contexts file. Example validating file_contexts file:
    checkfc out/target/product/generic/root/sepolicy out/target/product/generic/root/file_contexts
    

  • Example validating property_contexts file:
    checkfc -p out/target/product/generic/root/sepolicy out/target/product/generic/root/property_contexts
  • checkseapp - Used to parse the seapp_contexts file against the binary policy sepolicy. This is to ensure policy related information is valid (e.g. checks booleans, types, levels etc.).
  • insertkeys.py - Used to replace keywords in the signature sections of the mac_permissions.xml and mmac_types.xml files with keys obtained frompem files. This uses information contained in the external/sepolicy/keys.conf file that is detailed in the keys.conf section. This utility will also strip files of comments.
  • setool - This is not used by the actual build process but assists in generating new entries for the mac_permissions.xml file. It will extract permissions from one or more packages with their signatures then generate the package sections. Its output may need to be modified before inclusion in the master file as detailed in the setool section.

Modifying and Reloading Policy

This is covered at SEforAndroid - Policy in detail. This section gives a brief overview:
  • Modify the required policy source files, then regenerate the kernel policy file by:
make sepolicy
  • Copy the policy file to the device:
adb push out/target/product/<device>/root/sepolicy /data/security
  • Then load the new policy by:
adb shell su 0 setprop selinux.reload_policy 1

Middleware MAC

  • Install-time MAC (merged to seandroid),
  • Permission revocation (revoke-perms),
  • Intent MAC (intent_mac).

Install-time MAC

1. This mechanism applies an install-time check of app permissions against a MAC policy configuration (found in external/sepolicy/mac_permissions.xml in the source tree and as /system/etc/security/mac_permissions.xml on the system image).

2. The main code for the service is 
frameworks/base/services/java/com/android/server/pm/SELinuxMMAC.java

3. The persist.mmac.enforce system property controls whether the MAC restrictions are enforced; this can be set via SEAdmin app or via setprop.

4. The setool program can be used to generate policy stanzas for mac_permissions.xml, or to check whether a given apk would violate a given mac_permissions.xml configuration.
setool --build whitelist /path/to/foo.apk
setool --policy /path/to/mac_permissions.xml /path/to/foo.apk

5. Install-time MMAC policy that checks whether app permissions are allowed or not. If not allowed, the app cannot be installed or if the app is already installed before the updated policy, then the app cannot be run after the update.

Premission Revocation

1. A revoked permission list is maintained for each package and checked at runtime on permission checks. 

2. A revoked permissions configuration (found in external/mac-policy/revoke_permissions.xml in the source tree and as etc/security/revoke_permissions.xml on the system image) can specify revocation lists that are applied automatically on each boot.

3. Revoke permissions policy that checks whether the policy configured permissions on a package basis will be revoked at run time. If not allowed, that permission will be revoked (i.e. allow all unless specifically revoked). This is an optional policy and does not require any specific SELinux policy support.

4. The file that configures the policy is the revoke_permissions.xml and by default is installed at:
/system/etc/security/revoke_permissions.xml

5. The main code for the service is self contained in:
frameworks/base/services/java/com/android/server/pm/PackageManagerService.java

Intent MAC

1. Intent MAC supports a white-list of Intents and the types of their sources and destinations.

2. Currently, we only protect delivery of Intents to Activities, Broadcast Receivers, and Services. Content Providers are not yet protected.

3. Intent MMAC policy that checks whether the policy configured app intents (on a package and/or signature basis) are allowed or not at run time. If not allowed, that intent will not be sent.

4. The files that configure policy are intent_mac.xml and mmac_types.xml and by default they are installed at: 
/system/etc/security/intent_mac.xml
/system/etc/security/mmac_types.xml

5. The main code for the service is
frameworks/base/core/java/andriod/content/pm/IntentMAC.java and MMACtypes.java


auditd Daemon


The majority of this text has been extracted from system/core/auditd/README that describes its configuration, however note that:
  • Kernel auditing is included by default when building the SE for Android supplied kernels (e.g. for goldfish kernel see thekernel/goldfish/arch/arm/configs/goldfish_arm7_defconfig file) and auditd daemon is also included by default (seebuild/target/product/core.mk - under the SELinux packages).
  • The audit daemon output is formatted so that ausearch(8) can be used to search for SELinux events.




reference:

2013年5月23日 星期四

Android SDK Commands

# Android模擬器命令列啟動模式
在android-sdk-windows-1.1\tools執行emulator以執行模擬器
加上-skin參數,指定顯示模式為HVGA-L,則可轉為橫向
emulator - skin HVGA-L (480*320,水平顯示)
emulator - skin HVGA-L (320*480,垂直顯示,模擬器預設模式)
emulator - skin HVGA-L (320*240,水平顯示)
emulator - skin HVGA-L (240*320,垂直顯示)

# 使用mksdcard指令模擬1GB的記憶卡
mksdcard 1024M sdcard.img

# 模擬插入 SD 卡的模擬器
emulator - sdcard sdcard.img

# 使用 adb+push 上載檔案到SD記憶卡
adb push 001.jpg /sdcard (複製檔案到 /sdcard 目錄下)
adb push pictures /sdcard (複製 picture 照片目錄到 /sdcard 目錄下)
adb push mp3 /sdcard (複製 mp3 音樂目錄到 /sdcard 目錄下)
adb shell (Android 模擬器啟動命令列模式)
#cd /sdcard (進入 /sdcard 目錄)
#ls (查看 SD 記憶卡中的檔案)

# 使用 adb+pull 從 SD 記憶卡下載檔案
adb pull /sdcard/001.jpg . (下載 /sdcard 目錄下的檔案)
adb pull /sdcard/pictures . (下載 sdcard 目錄下的 pictures 目錄)

# 刪除 SD 卡裡面的檔案
adb shell
#ced /sdcard
#rm 001.jpg (刪除 SD 記憶卡裡的檔案)
#rm -r * (刪除 SD 記憶卡裡所有檔案與目錄)

# Android模擬器影片播放方法
mksdcard 4096M video.img (製作一個影像檔的 SD 記憶卡)
adb push video.avi /sdcard (從電腦複製影像檔到 SD 卡中)
emulator -sdcard video.img (啟動模擬器並載入 SD 卡)
下載免費的影片播放軟體,ex: Meridian Video Player (iiivpa.apk)
http://sites.google.com/site/eternalsandbox/Home/meridian-video-player
adb install iiivpa.apk (安裝Meridian Video Player)
接下來就可以用裝上去的player播放.mp4、3gp與.wmv三種檔案格式

# 安裝 APK 應用程式
adb install filename.apk (安裝filename.apk)
adb install -r filename.apk (保留已設定資料,重新安裝filename.apk)
adb -s emulator-5554 install filename.apk (指定安裝 APK 套件在 5554 的 Android 模擬器中)

# 移除 APK 應用程式
adb uninstall package
adb uninstall -k package (移除程式時,保留資料)
此package名稱不是安裝APK套裝時的檔名或顯示在模擬器中的應用程式名稱
可以先到/data/data或data/app目錄下,查詢想移除的package名稱
adb shell
ls /data/data 或 /data/app (查詢 Package 名稱)
exit
adb uninstall package (移除查詢到的 Package)

# ADB 系統除錯與連結工具
$adb devices (顯示目前有多少個模擬器正在執行)
$adb -s <serialNumber> <command> (指定模擬器來操作)
adb -s emulator-5554 install email.apk
$adb install apkfile (安裝 APK 應用程式套件)
adb install email.apk
$adb uninstall package (移除 APK 應用程式套件)
adb uninstall com.android.email
$adb shell (進入 Android 系統指令列模式)
$ls
$dmesg (查看 Android Linux Kernel 運作訊息)
ls - 顯示檔案目錄
cd - 進入目錄
rm - 刪除檔案
mv - 移動檔案
mkdir - 產生目錄
rmdir - 刪除目錄

$adb push <file/dir> (複製檔案到 SD 卡)
adb push mp3 /sdcard
$adb pull <file/dir> . (從 Android 系統下載檔案)
adb pull /data/app/com.android.email
$adb logcat (監控模擬器運作紀錄,以Ctrl + c 離開監控模式)
$adb bugreport (產生 adb 除錯報告)
$adb get-state (獲得 adb 伺服器運作狀態)
$adb start-server (啟動 adb 伺服器)
$adb kill-server (關掉 adb 伺服器)
$adb forward tcp:6100 tcp:7100 (更改模擬器網路 TCP 通訊埠)
$adb shell ps -x (顯示 Android 上所有正在執行的行程)
$adb version (顯示 adb 版本)
$adb help (顯示 adb 指令參數)

# Emulator 命令列啟動參數
emulator -timezone Asia/Taipei (指定時區)
emulator -no-boo-anim (省略開機小機器人動畫畫面)
emulator -scale auto (調整模擬器視窗大小)
emulator - scale factor (factor: 0.1-3.0)
emulator -dpi-device 300 (更改模擬器的解析度,default為 165dpi)
emulator -skin <skinID> (更改模擬器顯示模式)
emulator -help-keys (顯示鍵盤快速鍵說明)
emulator -shell (相當於adb shell 功能)
emulator -data data.img (使 /data 目錄使用 data.img 的檔案空間)
emulator -sdcard sdcard.img (使 /sdcard 目錄使用 sdcard.img 的檔案空間)
emulator -cache cache.img (瀏覽器暫存檔儲存空間)
emulator -wipe-data (使模擬器恢復到原廠設定)
emulator -help (顯示 emulator 指令參數) 


#Android : adb shell am 命令列啟動Activity或傳送Intent

例如:
//啟動瀏覽器,打開目標網址
adb shell am -a android.intent.action.VIEW -d http://www.google.com
adb shell am broadcast -a org.meshpoint.anode.START -e cmdline /data/tmp/hello.js
//撥打電話,號碼是123456789
adb shell am start -a android.intent.action.CALL -d tel:123456789
am start -a android.intent.action.CALL -d tel:123456789
Starting: Intent { action=android.intent.action.CALL data=tel:123456789}

輸入按鍵 : adb shell input keyevent [KEY ID]
      例如,想要「解鎖」就鍵入「adb shell input keyevent 82」
     00 -> "KEYCODE_UNKNOWN"
     01 -> "KEYCODE_MENU"
     02 -> "KEYCODE_SOFT_RIGHT"
     03 -> "KEYCODE_HOME"
     04 -> "KEYCODE_BACK"
     05 -> "KEYCODE_CALL"
     06 -> "KEYCODE_ENDCALL"
     07 -> "KEYCODE_0"
     16 -> "KEYCODE_9"
     17 -> "KEYCODE_STAR"
     18 -> "KEYCODE_POUND"
     19 -> "KEYCODE_DPAD_UP"
     20 -> "KEYCODE_DPAD_DOWN"
     21 -> "KEYCODE_DPAD_LEFT"
     22 -> "KEYCODE_DPAD_RIGHT"
     23 -> "KEYCODE_DPAD_CENTER"
     24 -> "KEYCODE_VOLUME_UP"
     25 -> "KEYCODE_VOLUME_DOWN"
     26 -> "KEYCODE_POWER"
     27 -> "KEYCODE_CAMERA"
     28 -> "KEYCODE_CLEAR"
     29 -> "KEYCODE_A"
     54 -> "KEYCODE_Z"
     55 -> "KEYCODE_COMMA"
     56 -> "KEYCODE_PERIOD"
     57 -> "KEYCODE_ALT_LEFT"
     58 -> "KEYCODE_ALT_RIGHT"
     59 -> "KEYCODE_SHIFT_LEFT"
     60 -> "KEYCODE_SHIFT_RIGHT"
     61 -> "KEYCODE_TAB"
     62 -> "KEYCODE_SPACE"
     63 -> "KEYCODE_SYM"
     64 -> "KEYCODE_EXPLORER"
     65 -> "KEYCODE_ENVELOPE"
     66 -> "KEYCODE_ENTER"
     67 -> "KEYCODE_DEL"
     68 -> "KEYCODE_GRAVE"
     69 -> "KEYCODE_MINUS"
     70 -> "KEYCODE_EQUALS"
     71 -> "KEYCODE_LEFT_BRACKET"
     72 -> "KEYCODE_RIGHT_BRACKET"
     73 -> "KEYCODE_BACKSLASH"
     74 -> "KEYCODE_SEMICOLON"
     75 -> "KEYCODE_APOSTROPHE"
     76 -> "KEYCODE_SLASH"
     77 -> "KEYCODE_AT"
     78 -> "KEYCODE_NUM"
     79 -> "KEYCODE_HEADSETHOOK"
     80 -> "KEYCODE_FOCUS"
     81 -> "KEYCODE_PLUS"
     82 -> "KEYCODE_MENU"
     83 -> "KEYCODE_NOTIFICATION"
     84 -> "KEYCODE_SEARCH"
     85 -> "TAG_LAST_KEYCODE"

   
#Android : aapt 使用
1. aapt l[ist] [-v] [-a] file.{zip,jar,apk}
List contents of Zip-compatible archive.
1.1 列出壓縮檔目錄
aapt l <file_path.apk>
參數:
-v:會以table的形式輸出目錄,table的表目有:Length、Method、Size、Ratio、Date、Time、CRC-32、Name。
其中Method表示壓縮形式,有:Deflate及Stored兩種,即該Zip目錄採用的演算法是壓縮模式還是存儲模式;可以看出resources.arsc、*.png採用壓縮模式,而其它採用壓縮模式。
Ratio表示壓縮率。CRC-32未明其意,Sodino盼指教。

-a:會詳細輸出所有目錄的內容。

2. aapt d[ump] [--values] WHAT file.{apk} [asset [asset ...]]
badging Print the label and icon for the app declared in APK.
permissions Print the permissions from the APK.
resources Print the resource table from the APK.
configurations Print the configurations in the APK.
xmltree Print the compiled xmls in the given assets.
xmlstrings Print the strings of the given compiled xml assets.

2.1 查看apk包的packageName、versionCode、applicationLabel、launcherActivity、permission等各種詳細資訊
aapt dump badging <file_path.apk>

2.2 查看許可權
aapt dump permissions <file_path.apk>

2.3 查看資源清單
aapt dump resources <file_path.apk>
一般都會輸出很多的資訊,如要全部查看,請用下麵這兩句:
aapt dump resources <file_path.apk> > sodino.txt
sodino.txt
這樣會把所有的資訊通過重定向符">"輸出到sodino.txt檔中,然後再打開該檔即可查看。

2.4 查看apk配置資訊
aapt dump configurations <file_path.apk>


2.5 查看指定apk的指定xml檔。
aapt dump xmltree <file_path.apk> res/***.xml
以樹形結構輸出的xml資訊。
aapt dump xmlstrings <file_path.apk> res/***.xml
輸出xml檔中所有的字串資訊。




Reference:
1. http://fecbob.pixnet.net/blog/post/35827899-android-aapt%E4%BD%BF%E7%94%A8

2013年5月15日 星期三

SELinux Notes -- Part I, Overview

SELinux by Example: Using Security Enhanced Linux
By Frank Mayer,, Karl MacMillan,, David Caplan

=======================================================

  • SELinux access control is based on a security context associated with all system resources including processes. The security context contains three elements: user, role, and type identifiers. The type identifier is the primary basis for access control.
    In SELinux, type enforcement is the primary access control feature. Access is granted between subjects (that is, processes) and objects by specifying allow rules that have the subject's type (also called a domain type) as the source and the object's type as the target. Access is granted for specified object classes using a fine-grained set of permissions defined for each object class.
    One of the key benefits of type enforcement is the ability to control which programs may run with a given domain type, thereby allowing access control down to individual programs (rather than the less-secure level of a user). The capability for a program to enter into a domain (that is, run with a given process type) is called domain transition and is tightly controlled by SELinux allow rules. SELinux also allows domain transitions to occur automatically through the type_transition rule.

  • SELinux does not directly use the role identifiers in a security context for access control. Instead, all access is controlled based on types. Roles are used to associate the allowed domain types into which a process running on behalf of a user may transition. This allows sets of type enforcement allowed capabilities to be grouped together and authorized for a user as a role.

Type Enforcement Access Control


In SELinux, all access must be explicitly granted. SELinux allows no access by default, regardless of the Linux user/group IDs. Yes, this means that there is no default superuser in SELinux, unlike root in standard Linux.

An allow rule has four elements:
  • Source type(s) Usually the domain type of a process attempting access
  • Target type(s) The type of an object being accessed by the process
  • Object class(es) The class of object that the specified access is permitted
  • Permission(s) The kind of access that the source type is allowed to the target type for the indicated object classes
As an example, take the following rule:
allow user_t bin_t : file {read execute getattr};


The translation of this rule would be as follows:

A process with a domain type of user_t can read, execute, or get attributes for a file object with a type of bin_t.




Example: passwd program
allow passwd_t shadow_t : file {ioctl read write create getattr setattr lock relabelfrom relabelto append unlink link rename};




In this example, we defined two types. The passwd_t type is a domain type intended for use by the password program. The shadow_t type is the type for the shadow password file. If we examine such a file on disk, we would see something like this:
# ls -Z /etc/shadow
-r----  root   root  system_u:object_r:shadow_t  shadow

Likewise, examining a process running the password program under this policy would yield this:
# ps -aZ
joe:user_r:passwd_t   16532 pts/0    00:00:00 passwd

The purpose of this rule is to give the passwd process' domain type (passwd_t) the access to the shadow's file type (shadow_t) needed to allow the process to move and create a new shadow password file.





Above figure shows an example of passwd program security in SELinux. The first rule is as follows:
allow user_t passwd_exec_t : file {getattr execute};

What this rule does is allow Joe's shell (user_t) to initiate an execve() system call on the passwd executable file (passwd_exec_t). The SELinux execute file permission is essentially the same permission as x access for files in standard Linux.


The next allow rules is
allow passwd_t passwd_exec_t : file entrypoint;

This rule provides entrypoint access to the passwd_t domain. The entrypoint permission is a rather valuable permission in SELinux. What this permission does is define which executable files (and therefore which programs) may "enter" a domain.



Let's now look at the final rule:
allow user_t passwd_t : process transition;

This is the first allow rule we have seen that did not provide access to file objects. In this case, the object class is process, meaning the object class representing processes. Recall that all system resources are encapsulated in an object class.




These three rules together provide the necessary access for a domain transition to occur. For a domain transition to succeed, all three rules are necessary; alone, none is sufficient. Therefore, a domain transition is allowed only when the following three conditions are true:

  1. The process' new domain type has enTRypoint access to an executable file type.
  2. The process' current (or old) domain type has execute access to the entry point file type.
  3. The process' current domain type has transition access to the new domain type.

When all three of these permissions are permitted in a TE policy, a domain transition may occur. Further, with the use of the entrypoint permission on executable files, we have the power to strictly control which programs can run with a given domain type. The execve() system call is the only way to change a domain type, giving the policy writer great control over an individual program's access to privilege, regardless of the user who may be invoking the program.


Default Domain Transitions: type_transition Statement



To support domain transitions occurring by default (as we want in the case of the password program), we need to introduce a new rule, the type transition rule (type_transition). This rule provides a means for the SELinux policy to specify default transitions that should be attempted if an explicit transition was not requested.

type_transition user_t passwd_exec_t : process passwd_t;

The syntax of this rule differs from the allow rule. There are still source and target types (user_t and passwd_exec_t, respectively) and an object class (process). However, instead of permissions, we have a third type, the default type (passwd_t).
Type_transition rules are used for multiple different purposes relating to default type changes.

The type_transition rule indicates that, by default on an execve() system call, if the calling process' domain type is user_t and the executable file's type is passwd_exec_t , a domain transition to a new domain type (passwd_t) will be attempted.


The type_transition rule allows the policy writer to cause default domain transitions to be initiated without explicit user input. This makes type enforcement less obtrusive to the user.


Role-Based Access Control (RBAC)


The RBAC feature of SELinux is built upon type enforcement; access control in SELinux is primarily via type enforcement. Roles limit the types to which a process may transition based on the role identifier in the process' security context.

We have added the role portion (user_r) of the security contexts for the processes depicted. We also added a new rule, specifically the role statement:
role user_r type passwd_t;

The role statement declares role identifiers and associates types with the declared role. The previous statement declares the role user_r (if it has not already been declared in the policy) and associates the type passwd_t with the role. What this association means is that the passwd_t type is allowed to coexist in a security context with the role user_r. Without this role statement, the new context joe:user_r:passwd_t could not be created, and the execve() system call would fail, even though the TE policy allows Joe's type (user_t) all the necessary access.

Role-based access control (RBAC) is a general security model that simplifies administration by assigning roles to users and then assigning permissions to those roles. RBAC in Security-Enhanced Linux (SELinux) acts as a layer of abstraction between the user and the underlying type-enforcement (TE) model, which provides highly granular access control but is not geared for ease of management.



Multilevel Security in SELinux (MLS)

The security level used by MLS systems is a combination of a hierarchical sensitivity and a set (including the null set) of nonhierarchical categories. These sensitivities and categories are used to reflect real information confidentiality or user clearances. In most SELinux policies, the sensitivities (s0, s1, ...) and categories (c0, c1, ...) are given generic names, leaving it to userspace programs and libraries to assign user-meaningful names. (For example, s0 might be associated with UNCLASSIFIED and s1 with SECRET.)
To support MLS, the security context is extended to include security levels as such these:
user:role:type:sensitivity[:category,...][-sensitivity[:category,...]]

Notice that the MLS security context must have at least one security level (which is composed of a single sensitivity and zero or more categories), but can include two security levels. These two security levels are called low (or current for processes) and high (or clearance for processes), respectively. If the high security level is missing, it is considered to be the same value as the low (the most common situation).

There are four dominance operators that can relate two MLS security levels are as follows:
dom:
(dominates) SL1 dom SL2 if the sensitivity of SL1 is higher or equal to the sensitivity of SL2, and the categories of SL1 are a superset of the categories of SL2.
domby:
(dominated by) SL1 domby SL2 if the sensitivity of SL1 is lower than or equal to the sensitivity of SL2, and the categories of SL1 are a subset of the categories of SL2.
eq:
(equals) SL1 eq SL2 if the sensitivity of SL1 and SL2 are equal, and the categories of SL1 and SL2 are the same set.
incomp:
(incomparable or noncomparable) SL1 incomp SL2 if the categories of SL1 and SL2 cannot be compared (that is, neither is a subset of the other).

SELinux Policy Server Architecture



In the policy server architecture, all manipulation and management of the overall system policy is controlled through the policy management server (PMS). The PMS is itself a userspace object manager in that it creates object classes representing policy resources and enforces a fine-grained access control policy over those resources.

With the PMS, you can now allow access to portions of the policy and limit access to others. For example, the SELinux policy can allow user management tools to add users and make role assignments, but not change type enforcement allow rules. Better yet, you can authorize a database server to change type enforcement (TE) rules relating to its object classes and types, but not those of the kernel. Internally, the PMS is designed to use another recent new feature of SELinux, loadable policy modules.


The second major function of the PMS is to split the system policy into kernel and user portions and load them respectively into the kernel security server and userspace security server (USSS). In this way, the kernel is not made aware of rules and object classes of concern only to userspace object managers. Userspace object managers query the USSS and not the kernel. AVCs in various userspace object managers register with the USSS (and not the kernel) for policy update and cache coherency functions.



SELinux Policy Language


The first section of a policy source file defines the object classes to the security server. This section also defines the permissions for each object class. For the kernel, these classes are directly related to kernel source files. In general, as an SELinux policy writer you would never change or modify the object class and permission definitions. 

The next section contains the type enforcement statements, which is by far the largest portion of an SELinux policy. This is the section that policy writers spend most of their time writing. It contains all the type declarations and all the TE rules (including all allow, type_transition, and other TE rules).

The next section of a policy source file contains the constraints. Constraints provide a means of further limiting the TE policy beyond what the TE rules permit. The multilevel security (MLS) policy, for example, is implemented as a set of constraints.

The last section of a policy file contains labeling specifications. All objects must be labeled with a security context for SELinux to enforce access control. This section tells SELinux how to treat filesystems for the purpose of labeling and contains the rules for labeling transient objects that are created at runtime. A separate related mechanism, called a file contexts file, is used to initialize the security context labeling of files, directories, and other objects on permanent filesystems.

Building and Installing Monolithic Policies


Above figure shows  a typical way that a policy is constructed.

Starting from the left side of this figure, you have the source files for the policy broken down into many tens of individual source modules. Compile the source policy using checkpolicy into a binary policy file, load_policy program is then used to load the binary policy file into the kernel, which then enforces access control based on the policy rules.
policy
Make policy.conf and policy.[ver] locally to test the compilation and check for error.
install
Do everything that make policy does plus install the binary policy file such that it will be loaded into the kernel at boot time and the policy configuration files.
load
Do everything that make policy does plus immediately load the binary policy file into the kernel as the active access control policy and install the file_contexts file.


2013年5月8日 星期三

Android 4.2 Multi-User

Setps to add users to Android 4.2

adb shell
su
pm get-max-users (should show 1)
setprop fw.max_users number (some number above 2)
pm create-user someusername 

repeat the create-user as wanted

Problem when testing on emulator 

Do't know how to switch from any non-primary user back to the primary(as far as using a visual UI)

Source Codes

User Management App


Reference:

2013年5月5日 星期日

Decompile APK


Reference: 

http://stackoverflow.com/questions/3593420/android-getting-source-code-from-an-apk-file

Procedure for decoding .apk files, step-by-step method:

Step 1:

Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk file to .zip (eg.: rename from filename.apk to filename.apk.zip) and save it. Now you get classes.dex files, etc. At this stage you are able to see drawable but not xml and java files, so continue.

Step 2:

Now extract this zip apk file in the same folder (or NEW FOLDER). Now download dex2jar from this link http://code.google.com/p/dex2jar/ and extract it to the same folder (or NEW FOLDER). Now open command prompt and change directory to that folder (or NEW FOLDER). Then write dex2jar classes.dex and press enter. Now you get classes.dex.dex2jar file in the same folder. Then download java decompiler from http://java.decompiler.free.fr/?q=jdgui and now double click on jd-gui and click on open file. Then open classes.dex.dex2jar file from that folder. Now you get class files and save all these class files (click on file then click "save all sources" in jd-gui) by src name. At this stage you get java source but the xml files are still unreadable, so continue.

Step 3:

Now open another new folder and put these files
1. put .apk file which you want to decode
2. download apktool v1.x AND apktool install window using google and put in the same folder
3. download framework-res.apk file using google and put in the same folder (Not all apk file need framework-res.apk file)
4. Open a command window
5. Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
6. apktool d "fname".apk ("fname" denotes filename which you want to decode)
now you get a file folder in that folder and now you can easily read xml files also.

Step 4:

It's not any step just copy contents of both folder(in this case both new folder)to the single one
and now enjoy with source code...

=================================================


Reference:


功能

  1. 集成apktool/dex2jar/jd-gui
  2. 只需执行一步即可反编译出apk所有文件(资源文件和jar等等)
  3. 打开jd-gui反编译jar文件

使用方法

  1. 在Downloads中下载onekey-decompile-apk.zip, 解压缩到类似D:\downloads\onekey-decompile-apk
  2. 将apk文件放到onekey-decompile-apk目录下
  3. 将apk文件拖拽到_onekey-decompile-apk.bat
  4. 执行完成后
    • 会在onekey-decompile-apk目录下生成和apk同名的目录(放置了apktools反编译出来的东西)
    • 会在onekey-decompile-apk目录下生成和apk同名的jar文件(dex2jar反编译出来的class)

运用工具(非常感谢他们)

  1. apktool反编译出apk中的资源文件, 例如AndroidManifest.xml和res
  2.     java -jar apktool.jar d -d xxx.apk
  3. dex2jar反编译出apk中的class
  4.     // dex2jar is deprecated, use the d2j-dex2jar
        d2j-dex2jar xxx.apk
  5. jd-ui/jad反编译class为java源文件
  6. 反编译工具还是jad最强, JD-GUI只是方便反编译/查看整个jar而已, 反编译出来的代码不全, 因此需要jd + jad(或者jadclipse eclipse插件使用更方便)配合才完美

参考

更新

  • 2012-10-24: inject_classes v1.0 将自己写的class混编(注入)到需要反编译的apk(mix/inject classes2apk) Changes
  • 2012-10-22: onekey-decompile-apk v1.0.1 将apktool降到1.4.1(原来是1.4.3), 只有这个版本能进行SmaliDebugging Changes
  • 2012-10-22: 新的一步到位打包apk(签名, 安装)工具(onekey build-sign-install apk). Changes