You are currently browsing the monthly archive for July 2010.

It is highly recommended to go through the following links first

In this grammar file we do our semantic analysis, by walking and evaluating the nodes, of the AST tree, generated in our grammar file.

Figure 1. A Snapshot of the tree of a statement.

tree grammar StatementWalker1;

options {

language = Java;

tokenVocab = XL1;

ASTLabelType = CommonTree;



package com.fawad.policywritingtool;



: (mode ‘(””‘ appname ‘”‘ ‘as’ app ‘,’ ‘”‘ permname'”‘ ‘as’ perm ‘)’ ‘:’

statement+ ‘->’ policyeffect ‘(‘app ‘,’ perm ‘)’ ‘;’ )+






: IDENT(‘.’ IDENT | ‘_’ IDENT)+






: IDENT+'()’



: IDENT(‘.’ IDENT | ‘_’ IDENT)+





An integer ‘result’ is returned when the statement is evaluated

statement returns [int result] :    e=expression  { result = e; }


Following are the operators and their respective implementation in the walker

expression returns [int result]

: ^(‘AND’ op1=expression op2=expression ) { if(op1==1 && op2 == 1) result =1; else result =0;}

|^(‘OR’ op1=expression op2=expression ) { if(op1==1 || op2 == 1) result =1; else result =0;}

|^(‘>’ op1=expression op2=expression) { result= op1 > op2?1:0; }

| ^(‘<‘ op1=expression op2=expression) { result= op1 < op2?1:0;}

| ^(‘>=’ op1=expression op2=expression) { result= op1 >= op2?1:0;}

| ^(‘<=’ op1=expression op2=expression) { result= op1 <= op2?1:0;}

| ^(‘=’ op1=expression op2=expression) { result= op1 != op2?1:0;}

| ^(‘!=’ op1=expression op2=expression) { result= op1 != op2?1:0;}

| ^(‘+’ op1=expression op2=expression) { result = op1 + op2; }

| ^(‘-‘ op1=expression op2=expression) { result = op1 – op2; }

| ^(‘*’ op1=expression op2=expression) { result = op1 * op2; }

| ^(‘/’ op1=expression op2=expression) { result = op1 / op2; }

| ^(‘%’ op1=expression op2=expression) { result = op1 \% op2; }

| ^(NEGATION e=expression) { result = -e;}

| TRUE{ result = 1;}

| FALSE{ result = 0;}

| INTEGER { result= Integer.parseInt($INTEGER.text); }


Policy effect returns an integer ‘res’ with the value ‘1’ for allow and  ‘0’ for deny

policyeffect returns [int res ]

: ALLOW {res= 1 ;}

| DENY {res= 0 ;}



Smartphones with open operating systems are getting popular with the passage of time. Increased exposure of open source smartphones also increased the security risk.  Android is one of the most popular open source operating system for mobile platforms. Android provide a base set of permissions to protect phone resources. But still the security area is underdeveloped. This survey is about the current work done on the Android operating system. Some of the techniques, which can give a positive edge to the security area, are analyzed in the present survey paper. These techniques are basically to provide a better security and to make the Android security mechanism more flexible. As the current security mechanism is too rigid. User does not have any control over the usage of an application. User has only two choices, a) allow all permissions and application will install, b) deny all permissions and installation will fail.


Smartphones are spreading day by day all over the world. However its security is still a big issue. The increased capability and computational power of smartphones increased the interest of developers towards the development of applications for this next generation platforms. Smartphones brings the mobility of traditional cell phones and the power of desktop computers in a single package. Weather updates, shopping, e-ticketing, mobile health and social networking, all on single platform with the additional factor of mobility. Where, the term mobility introduces, so the security and privacy becomes a major issue over there. In this emerging environment, applications are not stand alone. Applications expose its specific features to rest of applications installed on the same platform. And also use features of its neighbour applications. Where, this feature increases the functionality of an application, thereby it also welcomes some security threats. Which can’t be ignores in order to achieve a secure platform.

In the present environment of mobile platforms, Android is quite popular and famous open source and well customizable software package for cell phone devices. Android is a Google operating system for mobile platforms with the basic functionality of system utilities, middleware in form of VM and some core application like browser, dialler, calculator and some others as well.

The present applications are not enough to take full benefit of Android. So, third party developers create applications and launch it to the applications of Android Market. Users are able to download and install the launched applications. This is a sign of high availability of applications for users. But at the same time the user need trust full applications, which do not harm their privacy and security issues. Keeping this issue in mind, every application asks for permissions from the user during the time of installation. User has only two choices, either to grant all the required permissions and the application will be install. And once the permissions are granted, Android does not provide any facility to revoke those permissions, unless the user uninstalls the application.  If user denies the permissions so the application will fail installation. There is no mechanism to allow some permission and deny the rest.

Consider a weather update application that reads user’s location from his phone and provide weather updates on the base of time and location. Location information can be received by two ways. Either by taking location information automatically from GPS or the user himself enters his location where GPS is not available. At the time of installation, this application will ask for location permission. If the user grants the permission to the application so, the application will get install. The drawback is that, the application can collect the user location anytime, even user do not wish so. And if the user does not grant permission to the application during installation, so the application will not be install.

II. Background

Android is a Google operating system launched for mobile platforms. The current architecture of Android is explained below:

2.1 Android Layered Architecture

Android architecture composed of four layers. Application layer on top and the rest of three layers are beneath, application framework, Android runtime and Linux kernel.

Linux kernel is used as an abstraction the hardware and the software.

Android runtime’s is a core component of Dalvik virtual machine. Each Android process runs in a separate instance of Dalvik virtual machine.

Application Framework is a built in toolkit. It provides different packages of services to applications.

2.2    Android Application Structure

Android applications are written in java. But Android does not support execution of java byte code. Dx tool is used by Android for the conversion of java code into Dalvik byte code. Every application is assign with a unique Linux user ID call as UID. This functionality allows Dalvik to run multiple applications in a separate process. Those applications who run in a single process, must share a single UID. Otherwise every application will have a separate UID.

Figure 1: Typical ICC between Activities, Services, Content Providers and Broadcast Receivers

2.3    Android’s   Components

Android composed of basic four components. ICC is used for communication between components.

i) Activity: Activity is a visual screen for interaction of user with the application. Depends upon design, an application may consists of one or more activities

ii)Service: Service do not have a visual interface, it runs in the back ground, like play back music and fetching data from the network.

iii)Broadcast Receiver: Broadcast receiver receive broadcast announcements and response to them according to the situation.

iv)Content Provider: Content provider is a SQLite database, which supports the sharing and accessing of data among applications.

2.4    Android Security Policy Enforcement Mechanism

One of the major components of Android mandatory access control is Reference monitor. Which helps in the inter component communication (ICC).  Each component of an application is assign with some permission labels. These labels are used for interaction with the components of other applications. It is possible that a specific component of an application can interact with the component A of other application but can’t interact with the component B of the same application. This happens because of the permission assigns to each component of each application. Whenever a component wants to initiate ICC, the application checks the label of permissions. If the target component’s label is present in that bundle of permissions, ICC establishment is allowed to continue, otherwise denied.

In Android components interact with other components of same or other application through ICC mechanism based upon intents. Intents is mechanism for message passing, that also contains nature of the action to be performed. Intents can be sent to a specific component or can be broadcast to the Android framework. Android framework then passes it to the suitable component. Action strings help in specifying the intents, actually action strings show the type of action to be performed and then Android system take the decision that which component is suitable to perform the required action.

All the permissions are defined in the AndroidManifest.xml file. It also contains metadata related to security policy enforcement. <Permission>  tag specifies the components which can access it. <Intent-Filters>   specify those intents which can be resolved.

2.5    Protection Levels

Android has four permission levels, on the basis of which an application can be install.

i.  Normal: Normal permissions are granted without asking any permission from user.

ii.Dangerous: Dangerous permissions ask for the approval from the user at the time of installation. User has two choices, either grant all permission or deny all. Denying of permissions will stop installation.

iii.Signature: System grants these permissions if the requesting and granting application share the same certificate.

iv. Signature System:  Same as Signature but use for system applications only.

2.6    Limitations

Android permission lacks the modification of permissions. Android policy is very strict. It walks on all or nothing policy. User should allow all permission to allow any installation.

Android do not provide any runtime investigation for the behaviour of application. Once an application installed, so then it can every activity which it wants.

2.7   Mobile Phone Threats

  • Proof of concept: Keeping the Bluetooth device on without the knowledge of the user is an example of this threat. It drained device batteries.
  • Destructive: Deletion of phone book entries without the knowledge of user is an example of this threat.
  • Premeditated spyware:  This category includes location tracking and remote listening.
  • Direct payoff:  Sending sms without the permission of the user is a threat include in this category.
  • Information scavengers: Checking the address book, passwords and cookies without the permission of the user, lie down in this part.
  • Adware: The malware advertisements on cell phones are included in this category.

III.Extending Android Permission Model and Enforcement with User defined runtime constraints

In this paper, author presents a policy enforcement framework for framework for Android that allows users to grant permissions to applications on the basis of their needs. And also to impose constrains on the usage of resources.

3.1   Problem description

Android contain a suit of built in applications like dialler, browser and address book etc. Using the SDK developer can develop their own applications. Applications require some permission which is mentioned in the AndroidMamifest.xml.  These permissions are used for performing sensitive tasks like sms sending, using camera etc. At the time on installation Android asks user to grant permissions to the application to install. User does not have any other choice rather than granting all permissions to the application. Otherwise the application will not get install. Once the permissions are granted then user can not revoke those permissions until user uninstall the specific application.

Granting of a permission to an application results in providing unrestricted access to the resources. Android existing framework does not provide a security check on the usage of resources. For example, if once sms permission is granted to an application. So, that application can start sending sms any time. There is no way to stop it, unless user does not grant all permissions to it.

Four issues: (1) User must grant all permissions to install any application; (2) No way for restricting the granted permissions to an application; (3) As all permissions are based on install time checks, access to resources cannot be restricted based on dynamic constraints and (4) The only way of revoking permissions are to uninstall the application.

3.2   Android Permission Extension Framework

The existing Android application framework does not define specific entry point for execution of applications. There is no main function of applications, as applications are composed of components. So, components can communicate with components of other applications, if they permit them.

Different methods of ApplicationContext class in Android are used to handle the installation of these components. ApplicationContext acts as an interface for intents handling. With the rising of an intent, ApplicationContext two checks, that whether the permissions are associated with the intent and secondly, it checks whether the calling component has been granted with those permissions which are associated with the intent.

The ApplicationContext implements the IActivityManager interface. It uses the concept of binders and parcels, the Inter Process Communication for Android. Binder is the base class for remotable objects, that implements the IBinder interface and

Parcel acts as generic buffer for inter-process messages which are passed with the help of IBinder.

The ApplicationContext creates a parcel with the help of IActivityManager, and decide that calling application has specific permissions. The ActivityManagerService class receives this parcel and extract the PID, UID and the permissions associated with it. After that, send it to the checkPermission method of ActivityManagerService class. Then these arguments are passed to checkComponentPermission, it perform some checks. If the UID is root or system UID then it grants all permissions. For the rest, it will call PackageManagerService which extracts the package name for the pass UID and validate the permissions. If received permission does not match any of those present in the GrantedPermission so, it throws a security exception.

After checking the present security permissions, control is given to AccessManager. For the purpose a hook is placed in the CheckUidpermission of PackageManagerService. As it is the only entry point for permission checking. It throws the UID and the requested permissions to the AccessManager. AccessManager invokes PolicyResolver, it retrieves attached to the related application and using the PolicyEvaluatinonEngine, evaluate it. The policy includes the condition on the basis of which permissions will be denied or granted. EspressionParser retrieves the attribute of application from attribute repository and performs some sort of operations on these attributes.

3.3    Poly Android Installer

Writing policy is complex job for even system administrators. Android targeted at the consumer market and the end users as well. And users cannot complex usage policies. To end this problem the author created Poly. It is an advanced Android application installer. It provides user to specify constraints on the use of an application.

i) Allow: By default Android allows all permissions. This makes the existing Android installer a subset of Poly.

ii) Deny: This approach opposed the current approach of Android, which is all-or-nothing. As this approach give facility to the user to deny any permission by his owns choice. For example if Tom wants download an application and that specific application require some permission, sending sms is one of among those permissions. But Tom wants the application not to send any sms. So Tom will simply tap on the ‘send SMS’ permission and set it to ‘deny’. And still he may be able to install the application and enjoy the rest of facilities provided by that application.

3.4    Constraint Modification at Runtime

One of the limitations of Android security mechanism is the lack of ability of revoking permissions after an application get installs. Uninstalling of an application is the only way to revoke the permissions. Apex allows the user to specify his fine grained constraints at the time of installation through Poly. Once a user come to know that the application is not harmful, and he wants to assign more permissions to it, so Poly will help him in that. For example if a user install an application and grant it some permission and deny the permission of GPS. After some time he realize that this application not harmful and the user wishes to facilitate him with GPS facility as well. For modification the author created a shortcut to the constraint specification activity of Poly in the settings application of Android. ( class). This allows the user to modify constraints he specified at the time of installation. Even after, the application has been installed. And the same rule follows for denying of permissions after installation.

Figure 2: Android Permission Extension (Apex) Framework

IV. Mitigating Android Software Misuse Before It Happens

In this paper, author proposed a framework; know as Kirin to capture security policy that transcends Android applications. Stakeholders’ define some policy invariants, for sack of security. On the base of which, an application will be certified at the time of installation. Mobile phone operating system provides more open APIs for third party applications. That is why the security framework must not only provide per interface permissions, but it should also be capable of supporting “administrative” policies defined by all stakeholders’.

4.1   Contributions

  • The author reverse engineer Android’s security model and present it formally.
  • Author provides a framework for specifying and enforcing stakeholder security policy.
  • Prolog is used for install time installation. Prolog is a common language for security policy evaluation.
  • Author use the proposed framework to identify insecure application policy configurations within Android. Such applications can affect voice, SMS and location services.

4.2    Kirin

In this paper a model is proposed, which states that before   system install any downloaded application package, it must first ensure the applications satisfy all security requirements. If any requirements fail to met, the installation will be terminates. This model, of installation ensures the cell phone will remain in its original secure state, without based on user made security decisions.

The policy pre-processor extracts policy from the target applications package, and converts it to Prolog facts. After that it merges it with the existing policy knowledge. The result of the merger represents the security state of the system, if the installation were to proceed. The policy engine after that uses the temporary policy state to evaluate invariants. Policy engine extract invariants from system policy, user policy and applications policy. On the basis of these invariants, policy engine take the decisions. It automatically generates compliance proofs for the target application. If all the invariants satisfied, so installation will continue. If any of the invariant fails to satisfy so the installation will abort.

4.3 System invariants

Invariant 1: “An application must have explicit permission to make an outgoing voice call.”Android uses CALL_PHONE and CALL_PRIVILEGED permissions, to protect the API from making outgoing calls. An application holding the call permission can indirectly provides its API access via its components interface. This invariant makes it sure the no indirect access should be allowed.

Figure 3: Enhanced Installation Logic. New packages cannot be installed unless all policy in variants passes

Invariant   2: “An application holding a dangerous permission must have no unprotected components”

Android framework introduces “dangerous permissions”. Which states that user should allow permissions to applications at time of installation. For example, sensitive tasks like making call and sending SMS permissions are mark as dangerous. So that, any application asks from user before using these services.

Invariant   3: “Only system applications can interface with hardware”. Android framework introduces high level java APIs for interfacing with hard ware. For the sack of flexibility, Android let any application to interact with the APIs, but with proper permissions. This invariant insures only system applications have direct access to APIs.

4.4    User Privacy Invariants

Invariant 4: “Only system applications can process outgoing calls.”[2] Android framework let applications to receive notifications of outgoing calls, including the destination number. To keep the issue of privacy in eye, user may wish that only system applications should receive such notifications.

Invariant 5:  “Applications that can perform audio record must not have network access or pass data to

an application that has network access”. It is quite dangerous for security, if an application record voice and send it on internet.

Invariant 6: “An application with access to Wifi or Network state must also declare network access.”

4.5 Application invariants

Invariant 7:  “An application can only receive SMS notifications from trusted system components.”Any application has the ability to broadcast intent. But some intent can only be broadcast by system applications. This gives the surety that only system applications can send SMS.

Invariant 8: “An application can only receive location updates from trusted system components.”  Some applications take decision on the base of location so, only the system applications have the right to send the location notification.

4.6 Limitations

Kirin is limited to obtain data from application package metadata. Kirin does not provide any dynamic security check. Kirin provides only install time security.


The author proposed Kirin security service for Android, which provides a lightweight certification of application at the time on installation. To certify applications based on security configuration requires to clearly specifying the unwanted properties. For the identification of Kirin security rules, the author took help of security requirements engineering. On other hand a security language design has been defined, to implement Kirin security service within the Android framework.

  • Methodology for adding new security requirements and flaws in current Android are defined.
  • Practical method of performing lightweight certification of applications at install time is provided.
  • Mitigation of malware rules are mentioned.

5.1 Kirin Security Rules

Security requirements engineering is based upon three basics. 1) Operation of a system in normal environment, 2) assets are entities that someone places value upon, 3) security requirements are actually constraints on the functionality of system to protect assets.

5.2 Identifying Security Requirements

Existing security requirements engineering techniques are referred in order to identify dangerous application configuration.

Step 1: Identify Assets: Assets are defined from features of Android platform.  In the form of label permissions, assets are already defined by Google.

Figure 4: Sample Kirin security rules to mitigate malware

All components of system applications are assets basically. Android defines the RECORD_AUDIO permission to protect the audio recorder. Microphone is an asset in this example, as microphone records the voice of user. Permission are define by Android for making phone calls, and observation of phone state as well.

Step 2: Identify Functional Requirement: In this step the author studied the interaction of applications with phone and with third party applications. Assets and functional description plays a vital role in security threats. When an incoming call is receives so, the system broadcasts intent to the PHONE_STATE action string. And also notify the registered application with the PhoneStateListner. In the same way action NEW_OUTGOING_CALL action string is also broadcasted.

Step 3: Determine Assets Security Goals and Threats: Confidentiality, integrity and availability considers being high security goals. Determination of appropriate goals and determination of methods that how functional requirements can be abused with respect to the remaining security goals is important. If a voice call is record and sends on internet, it is against the confidentiality.

Step 4: Develop Asset’s Security Requirement: Next security requirement from the threat descriptions. Security requirements are constrains on functional requirements. Which defines who can exercise functionality.  Observations says that, eavesdropper requires a) notification of incoming or outgoing call, b) the ability to record audio and c) access to Internet. So an application must not have these rights at the once.

Step 5: Determine Security Mechanism Limitations: The goal of this step is to determine dangerous configurations at only install time. Author is limited to information available in an application manifest file. An application must not have permission for processing outgoing calls, record audio and internet permission.

5.3 Single Permission Security Rules

Dangerous permissions of Android may be too dangerous in some production environment. The SET_DEBUB_APP permission allows an application to turn the debugging for another application. The corresponding API is hidden in the most recent SDK. Third party does not have access to hidden APIs but it is not a substitute for security. Rule1 ensures third party applications do not have the SET_DEBUG_APP permission.

5.4 Multiple Permission Security Rules

Voice and location eavesdropping malware need permissions to record audio and access location information. But at same time legitimate applications also use these permissions. So a rule is need as multiple permission. Rule 2 and 3 protect against the voice eavesdropper. Rule 4 and 5 protect from location tracker.  Rule 6 protects from incoming malware SMS. Rule 6 and 7 consider malware interaction with messages. As SMS can be used as a path for malware. And malware owner will not let user let know about SMS, therefore content provider will be is modified just after receiving a SMS.  Rule 7 does not stop SMS sending, but increase the probability that user becomes aware of the activity. Rule8 makes use of the duality of permission labels.

Permissions are not always enough to differentiate between malware and legitimate behaviour. Rule 9 provides example of a rule considering both permission and an action string.  This stops a malware from replacing the default voice call dialler application without the awareness of the user.


Android system protects the phone from malicious applications, but with limited infrastructure for applications protection.

Permission assignment policy: Applications have limited ability to control, to which the permissions are granted for accessing their interface.

Figure 5: Policy tree illustrating the example policies required by applications

Interface exposure policy: Androids facility is too rigid for controlling of their interface for other applications.

Interface use policy: Limited means of selecting, at run-time, that which applications interface are accessible.

6.1 Application policies

Permission granting policy is an install time policy. Its subparts have a) Protection level based policy. Normal permissions are granted directly, Dangerous permissions are granted by the wish of user, Signature based permission allows only those permissions to be installed which are signed by the same developer. Signature system is used for system applications only. B) Signature based policy, this is same as signature based, but permissions can be allotted even if application A and B are signed by different developers. c) Applications configuration based policy. This policy keeps on check upon the application version etc.

Interaction policy is runtime policy. Its first three parts are as same as install time policy, but it just checks those permissions at runtime. Additional feature in runtime policy is context based policy. For example if a user do not want to allow GPS permission at specific day or time, or a game should not be start, if the battery is low that 10%.

6.2 Install time policy

Saint install-time policy regulates granting of application on the basis of mentioned permissions. An application define permissions, requested application should hold those permissions in order to communicate with the specific application.

AppPolicy provider takes the decision at time of installation and Saint installer enforce it. AppPolicy maintains record of all install and runtime policies. At the time of installation Android installer retrieves the permissions from the manifest file a) it check the AppPolicy provider for each permission. B) AppPolicy provider consults its policy database, and returns a result by keeping the rule in notice. C) installation will proceed only if the conditions satisfy.

6.2 Runtime Policy Enforcement

For the interaction of softwares components with in Android framework, IPC are used. Caller application sends the IPC and callee receives that IPC. If conditions of both caller and callee satisfy, then IPC continues.

First Saint Madiator retrieves policy file from the application, then send it to Saint AppPolicy provider, the conditions and permissions are checked there. If not satisfied, so the IPC is blocked. Otherwise the IPC is directed towards the current Android permission check and after that communication starts between two applications.

6.3 Administrative Policy

Administrative policy defines the control of user towards policy.  If user is not allowed to change the policy so, he cannot use it in very appropriate way. And if allowed to change then it is a compromise on security. Because user may changes it in wrong way. So author leaves this decision upon operating system. Two flags are defined, SaintOverride flag and Override flag. If both flags are yes, then user can change the policy.

Figure 6: Saint Enforcement –Saint enhances the application installation and interaction of policies.

6.4 Operational Policy

Operational policy consists of three type of conditions.

  • Always satisfied
  • Satisfiable
  • Unsatisfiable

6.5 Saint Architecture

Saint architecture was implemented as modification on Android. For policy enforcement, hooks are placed.

A)    Saint Installer:

It is a modified version of Android installer. Saint installer retrieves all permission from the application package, its version and signature etc. Saint policy is implemented in an XML file with the same name of the package. After parsing the package file, it checks the permissions, if do not satisfy so rejected.

B)    Saint Mediator:

1. Starting an Activity: Saint runtime enforcement consists of four components. Starting new activity, binding components to services, receiving broadcast intents and accessing content provider. For starting an activity, intent is generated, Activity Manager Service open the required program if the name of application is mentioned in the intent. But before starting a security hook will check the policy. If name of application is not mentioned in the intent so the intent will be handed over to Resolver activity. If single match found, so application will be started but a hook is there to check the policy. If multiple applications found for the raised intent, so a menu will be open in front of user, and user will select an application. But before that a hook will check the policy.

2. Receiving intent broadcast: Activity Manager will receive intent. If receiver name is mentioned so, it will receive it but a security hook is there to check the policy. If name of receiver is not mentioned first it will be checked in Dynamic BR list and after that in Static BR list. In both cases hook will be placed to check the policy before starting any activity.

3.Accessomg Content Provider: Any application wants to access content provider, so a hook is placed to check that weather the given application has the permissions to access the content provider .

4. Binding components to services: This allows binding intent to a service. Intent binds to a service either by its name mentioned in the intent or intent containing the action string to which the service is registered.


In this survey paper four approaches are discussed for the security of Android. Kirin and Lightweight approaches are basically install time approaches. If once an application grant some permissions, so there is no security mechanism through which Kirin or Lightweight keep check on the behaviour of application during runtime. Kirin cannot keep on check on dynamic broadcasts.

Light weight cannot directly utilize these existing techniques because the current techniques are structured to supplement system and software development. Lightweight cannot guarantee fixed number of SMS is sent during in specific period of time.

Comparatively to Kirin and Lightweight, Apex approach seems to be more feasible. As its architecture is simple and the property which give edge to Apex is its runtime policy. Which keep on check on the application behaviour at runtime, and on base of policy do not let an application to do something which permission is not grant to it. Still some problems are there, the installer currently incorporates a small number of constraints. For a larger user community, study of user requirements is required. Secondly it can create problems if user unknowingly grants such permissions to an application which can produce harmful results. This problem can be solved by the conjunction of Kirin with Apex, by analysing the constrains and permissions to verify that security rules are not being violated.

Also developer should mention in the manifest file of an application, that why the specific permission is required for the functionality of the application. For example, requesting GPS permission, the developer should mention that why GPS is needed by the application.

Semantic Rich Application Centric Security in Android is an approach for the security of Android. This approach provides a good security mechanism for install time, runt time and application to application interaction as well. In this approach security hooks are placed in every require place of Android framework for the insurance of security.

Courtesy of Kamran Habib Khan & Mir Nauman Tahir

These are some of the unforgettable moments that i caught on my xpress music 5220 nokia’s 2.0 MP camera.  The time taken to complete this album took almost a year and still i have certain friends in office that i havent caught on my camera yet. But i hope that in coming Ramazan i will get a chance to complete my album with the missing personalities.

Note: Dear friends its just part of some fun that i want to share with u all. If someone dont like it. plz let me know. i will remove his pic. I dont want to hurt any1. its just some fun. thats all. even my snap is there. sohail took it while i was sleeping. and that was the first time in the past 1 year that i slept and sohail didnt missed the chance. so its great fun.

thinking deeply on how to get winodows 7 running on Open Moko

writting policy for android in Antlr

sick of Identity Management thats why he is hiding his identity by hiding his face

trying to fit Security Enhanced PostgreSQL with OpenERP on a fedora OS with SELinux enabeled. Does that make any sense.

having sweet dreams of his life in spain. enjoying his scholorship.

waiting for spring....

that is our man, before he got married of course. now he can never sleep ever.....

have no worries. OpenERP is here. implement it. and forget everything....

may his soul rest in peace with unicorn, oh sorry i mean ucon ...

It is highly recommended that one should have at least a basic knowledge of Antlr, Lexer and Parsers, Tree Walker etc. For a light introduction of Antlr, Policy writing, Grammer or Lexer and Parsers etc and some operational basics please read our previous post at

The policy input expected by our grammar is as follows

restrict (“edu.ringlet.Ringlet” as Ringlet, “android.permission.SMS_SEND” as SMS) :

Ringlet.sentSms() < 5; -> allow(Ringlet, SMS) ;

1.    This is our Grammar file which specifies the rules(syntax and Semantics) of our high-level policy language. In this file the Lexer scans our language into tokens then the parser generates a tree out of the tokens to get some meaning out of it

grammar XL1;



2.    The Target language specified is Java

language = Java;

3.    This will output our grammar into an Abstract Syntax Tree




4.    Explicit Token used in negation of a term







package com.serg.policywritingtool;




package com.serg.policywritingtool;


5.    This is our main ‘policy rule’, which determines what input we should be expecting and in which order


: (mode ‘(””‘ appname ‘”‘ ‘as’ app ‘,’ ‘”‘ permname'”‘ ‘as’ perm ‘)’ ‘:’

statement+ ‘->’ policyeffect ‘(‘app ‘,’ perm ‘)’ ‘;’ )+ ;

6.    The Following Subrules used in the policy rule determines which input is a possible one and which is not. The first input rule ‘mode’ specifies that it can take lexer rule RES(explained below) only as input




7.    The appname rule takes IDENT followed by .IDENT or _IDENT.(the + sign states that this should occur at least one time)


8.    IDENT is discussed below

: IDENT(‘.’ IDENT | ‘_’ IDENT)+





9.    The appname rule takes IDENT followed by .IDENT or _IDENT (the + sign states that this should occur at least one time)


10. IDENT is discussed below

: IDENT(‘.’ IDENT | ‘_’ IDENT)+





11. Statement rule specifies that it takes expression rule followed by a semi-colon ‘;’ as input


:   expression ‘;’


12. Expression rule then specifies it takes two realtaions with an AND or OR in between


: relation ((‘AND’^ | ‘OR’^)relation)*


13. Realtion rule then specifies it takes two relations with an AND or OR in between

relation : add((‘=’^ | ‘!=’^ | ‘<‘^ | ‘<=’^ | ‘>’^ | ‘>=’^) add)*


14. Expression add then specifies it takes two mult terms  with a + or – in between


: mult((‘+’^ | ‘-‘^) mult)*


15. Expression mult then specifies it takes two unary terms  with a * or / in between


: unary((‘*’^ | ‘/’^ | ‘mod’^) unary)*



: (‘+’! | negation^)* not


16. Any ‘-‘ sign of a negation entered should be converted to our explicit Token defined


: ‘-‘ -> NEGATION


17. To neagte a logical operator the string literal ‘not’ is used


: ‘not’? term


18. A term is specified to be either an integer. app.method() name or can take the string literals (true or false)


:  app’.’method  | ‘(‘! expression ‘)’! |INTEGER | TRUE | FALSE



: IDENT+'()’


19. Policyeffect can only take lexer rules ALLOW or DENY as input




Policy identification

20. RES(a lexer rule) can only contain the string literals ‘restrict’ or ‘unrestrict’ anything else will give an error.


: ‘restrict’ | ‘unrestrict’


21. Lexer rule DENY can only take string literal deny as input


: ‘deny’


22. Lexer rule ALLOW can only take string literal allow as input


: ‘allow’


23. Lexer rule TRUE can only take string literal true as input


: ‘true’


24. Lexer rule FASLE can only take string literal false as input


: ‘false’


25. INTEGER rule specifies the input to be one or more integers from 0 to 9


: ‘0’..’9’+


26. WS is a whitespace character rule specifying space or end of line etc


: (‘ ‘|’\n’|’\t’|’\r’|’\f’)+ {$channel=HIDDEN;}


27. The lexer rule IDENT specifies that the input should be a sequence of one or more letters(small or upper case)


: (‘a’..’z’|’A’..’Z’)+


28. COMMENT rule allows us to add line comments in our high level language


: ‘//’ .* (‘\n’|’\r’){$channel=HIDDEN;}


29. Similar as COMMENT but for multiple lines


: ‘/*’ .* ‘*/’ {$channel=HIDDEN;}


1.       Get eclipse from (version eclipse classic 3.5.1)

2.       Download ANTLR at and click on “Complete ANTLR 3.2jar, all tools,runtime,etc” link

3.       After downloading antlr package create a folder named “ANTLR-3.2” and inside it create another folder “lib” and put antlr 3.2jar downloaded in step 2 in the lib directory.

4.       Move the antlr-3.2 directory into C drive(or any work folder for ubuntu), eclipse should be in the same directory

5.       For antlr plugin inclusion in eclipse goto the wiki link on the antlr homepage( and inside it click on “Integration with Development environments” and we get two chices underneath eclipse click on “Eclipse 3.3+ for antlr for ANTLR 3.x”. Init we have AntlrDT( a standard Eclipse plugin implementing an Antlr 3.1+ specific grammar editor, outline, and builder) and ANTLR IDE(an eclipse plugin for ANTLRv3 grammars which is required) optiions. click on and under download/install we get to know wht we need to do to get the setup complete for installing actual ANTLR plugin:

6.       eclipse 3.5 (we already downloaded it).

7.       GEF 3.2 (graphic editor framework for eclipse).

8.       zest 1.0.0 ( a simplification for graphs in eclipse inside the GEF.

9.       Dynamic Language Toolkit(DLTK) Core.

10.   Open eclipse save your select a destination to save your workspace e.g C:\Users\owais\workspace (/home/advo/workspace for ubuntu). to install the plugins goto help menu click on Install New Software, change the work with drop down meny to “Galileo- on the main plugin distribution site for the plugins to be downloaded from eclipse, uncheck the Group items by category to get GEF, zest and DLTK. To get DLTK type Dynamic languages in the search box for main plugin distribution site. you will get a list of available dynamic languages plugins. Check the “Dynamic Languages Toolkit-Core Frameworks”.

11.   To get GEF type GEF in search and check “Graphical Editing Framework GEF”.

12.   Type zest in the search to get available zest plugins and check “Graphical Editing Framework Zest Visualization                 Toolkit”.

13.   In order to make sure all three plugins got checked blank/remove anything entered in the search box to get all the                 available plugins list. Confirm all the three checkmarks are there by visual inspection.

14.   Click on next we will see all three plugins, and then click next and accept the license and click finish and restart to take effect.

15.   Now to download actual ANTLR IDE plugin on the download/install page on Antlr wiki copy the link and in eclipse goto help menu and open install new software option as we didi for previous plugins. On work with menu click on Add option and paste the copied link in the Location field and in name field enter ANTLR IDE. It will list the ANTLR IDE and we have to check everything available. Click next and further next check the accept license and click finish to install the plugin. during instalation we will get a warning, avoid it by clicking ok we will setup the IDE ourselves.Restart eclipse to take effect

16.   To setup ANTLR goto window menu and click on preferences. click on ANTLR and check the “mark generated resources as derived“. UNderneath ANTLR click on builder and define an antlr package. click on add and include the directory that we put ANTLR-3.2 into and click ok. underneath Code Generator check “Project relative folder” to keep generated files seperate from source files and give name to output folder name e.g antlr-generated and check “Append java package to output folder” and click Apply. Under editor  change Tab policy menu “Tabs only” and change identation size and displayed tab size to 4. Inside editor click on Content Assist and uncheck “Enable auto activation” and in folding option uncheck “enable folding“……. and click OK to complete to setup everything to create a project.

ANTLR, Another Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages.

Programmers usually use parser generators to build translators and interpreters for domain-specific languages such as proprietary data formats, common network protocols, text processing languages, and domain-specific programming languages.

Domain-specific languages are important to software development because they represent a more natural, high fidelity, robust, and maintainable means of encoding a problem than simply writing software in a general-purpose language. For example, NASA uses domain-specific command languages for space missions to improve reliability, reduce risk, reduce cost, and increase the speed of development. Even the first Apollo guidance control computer from the 1960s used a domain-specific language that supported vector computations.

This article will explain the main ANTLR components and explains how they all fit together.

A translator maps each input sentence of a language to an output sentence. To perform the mapping, the translator executes some code you provide that operates on the input symbols and emits some output. A translator must perform different actions for different sentences, which means it must be able to recognize the various sentences.

Recognition is much easier if you break it into two similar but distinct tasks or phases. The separate phases mirror how your brain reads English text. You don’t read a sentence character by character. Instead, you perceive a sentence as a stream of words. The human brain subconsciously groups character sequences into words and looks them up in a dictionary before recognizing grammatical structure. The first translation phase is called lexical analysis and operates on the incoming character stream. The second phase is called parsing and operates on a stream of vocabulary symbols, called tokens, emanating from the lexical analyzer. ANTLR automatically generates the lexical analyzer and parser for you by analyzing the grammar you provide.

Performing a translation often means just embedding actions (code) within the grammar. ANTLR executes an action according to its position within the grammar. In this way, you can execute different code for different phrases (sentence fragments). For example, an action within, say, an expression rule is executed only when the parser is recognizing an expression. Some translations should be broken down into even more phases. Often the translation requires multiple passes, and in other cases, the translation is just a heck of a lot easier to code in multiple phases. Rather than reparse the input characters for each phase, it is more convenient to construct an intermediate form to pass between phases.

Figure 1: Overall translation data flow; edges represent data structure flow, and squares represent translation phases

This intermediate form is usually a tree data structure, called an abstract syntax tree (AST), and is a highly processed, condensed version of the input. Each phase collects more information or performs more computations. A final phase, called the emitter, ultimately emits output using all the data structures and computations from previous phases.

Figure 1 illustrates the basic data flow of a translator that accepts characters and emits output. The lexical analyzer, or lexer, breaks up the input stream into tokens. The parser feeds off this token stream and tries to recognize the sentence structure. The simplest translators execute actions that immediately emit output, bypassing any further phases.

Another kind of simple translator just constructs an internal data structure, it doesn’t actually emit output. A configuration file reader is the best example of this kind of translator. More complicated translators use the parser only to construct ASTs. Multiple tree parsers (depthfirst tree walkers) then scramble over the ASTs, computing other data structures and information needed by future phases. Although it is not shown in this figure, the final emitter phase can use templates to generate structured text output.

A template is just a text document with holes in it that an emitter can fill with values. These holes can also be expressions that operate on the incoming data values. ANTLR formally integrates the StringTemplate engine to make it easier for you to build emitters. StringTemplate is a domain-specific language for generating structured text from internal data structures that has the flavor of an output grammar. Features include template group inheritance, template polymorphism, lazy evaluation, recursion, output autoindentation, and the new notions of group interfaces and template regions.2 StringTemplate’s feature set is driven by solving real problems encountered in complicated systems. Indeed, ANTLR makes heavy use of StringTemplate to translate grammars to executable recognizers. Each ANTLR language target is purely a set of templates and fed by ANTLR’s internal retargetable code generator.

For a more details on antlr visit the links in the references.


The Definitive ANTLR Reference: Building Domain-Specific Languages by Terence Parr

1.Download the recovery image form the link below. Use this image in case of  recovering from a disaster. Recovery Image: from

2. Copy to /source/ directory.

3. Go to ‘vendor/htc/dream’  and run ‘./’, or  ./

4. Then, Then apply the following commands

5. source build/

6. $ lunch aosp_dream_us-eng

7. Compile the modified Android Source Code for the device

8. $ make -j

9. Now the generated files are

10. boot.img,

11. recovery.img,

12. system.img,

13. userdata.img

14.  These files will be located at

15. out/target/product/dream-open/

16.  Put device into FASTBOOT mode

17. reboot

18. power_on the device with BACK key pressed,

19.  It should show the driods on skateboard with fastboot text displayed.

20.  Make sure the cable with the device is connected.

21.  Now apply the following commands

22. sudo su

23. set path to fastboot

24. export PATH=/mydroid/out/host/linux-x86/bin/:$PATH

25.  Stop and start the server

26. adb kill-server

27. adb start-server

28.  Check the fastboot devices

29. #fastboot devices

30.  The above command will show you the fastboot devices.

31. HT94JLZ00002    fastboot

32.  Now apply the following command.

33. #fastboot -p dream-open -w flashall

34.  flashall will apply all the above listed img files one by one. but we can also do that manually by specifying the image file name. After this the flashing will start and our device will be loaded with our own modified source code.

Blog Stats

  • 325,597 hits

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 233 other followers

%d bloggers like this: