Monkey source code analysis event injection and monkey source code injection

Source: Internet
Author: User

Monkey source code analysis event injection and monkey source code injection

In the previous article Monkey source code analysis event source in this series, we described how monkey obtained commands from the event source, and then converted the commands into events and put them in the event queue, however, we have not yet understood what the events in monkey are. This article uses this question as the starting point to try to figure out what the monkey event architecture is like, then why is this architecture, and how it injects events to trigger click and other actions.

Before reading this article, I hope you 'd better read several other blog posts first, so that you can understand them more easily:

  • Monkey source code analysis-Comparison of Three Android injection events
  • Monkey source code analysis: How WindowManager injection excludes inter-process security restrictions
  • Role of WindowManager in Android

1. Event architecture here we will first take a look at the MonkeyEvent-related part of the online Monkey architecture diagram in the previous article monkey source code analysis.
As you can see, MonkeyEvent defines three public methods and inherits five different classes. Each class corresponds to one event type:
  • MonkeyActivityEvent: indicates Activity-related events.
  • MonkeyMotionEvent: events related to Motion
  • MonkeyKeyEvent: events related to keys
  • MonkeyFlibEvent: events related to Flib
  • MonkeyThrottleEvent: A Sleep event
The figure also describes that this is a command design mode. In fact, the command design mode is not shown in this figure, next we will describe how it implements the command design pattern. Here we will take an example to see how the next specific event is made up. For consistency, we will describe an event from the network event source described in the previous article, here I picked MonkeyKeyEvent.
2. building MonkeyKeyEvent here we will not describe it in depth, because it only declares several methods, as long as the head knows that it declares a very important injectKeyEvent method, each subclass needs to implement it to inject events. Now let's take a look at the constructor of MonkeyKeyEvent:
public class MonkeyKeyEvent extends MonkeyEvent {    private long mDownTime = -1;    private int mMetaState = -1;    private int mAction = -1;    private int mKeyCode = -1;    private int mScancode = -1;    private int mRepeatCount = -1;    private int mDeviceId = -1;    private long mEventTime = -1;    private KeyEvent keyEvent = null;    public MonkeyKeyEvent(int action, int keycode) {        super(EVENT_TYPE_KEY);        mAction = action;        mKeyCode = keycode;    }    public MonkeyKeyEvent(KeyEvent e) {        super(EVENT_TYPE_KEY);        keyEvent = e;    }    public MonkeyKeyEvent(long downTime, long eventTime, int action,            int code, int repeat, int metaState,            int device, int scancode) {        super(EVENT_TYPE_KEY);        mAction = action;        mKeyCode = code;        mMetaState = metaState;        mScancode = scancode;        mRepeatCount = repeat;        mDeviceId = device;        mDownTime = downTime;        mEventTime = eventTime;    }
MonkeyKeyEvent has multiple constructors with different parameters, but only one objective. You can obtain sufficient information by passing in the parameters and save them as member variables so that you can create an android SDK in the future. view. keyEvent, because the system event can be initialized according to different parameters. For example, the following getEvent method creates the corresponding KeyEvent according to different parameters. Note that this system KeyEvent is very important, because in the future we will use the WindowManager injection event to upload its object to drive the corresponding key-related events.
     * @return the key event     */    private KeyEvent getEvent() {        if (keyEvent == null) {            if (mDeviceId < 0) {                keyEvent = new KeyEvent(mAction, mKeyCode);            } else {                // for scripts                keyEvent = new KeyEvent(mDownTime, mEventTime, mAction,                                        mKeyCode, mRepeatCount, mMetaState, mDeviceId, mScancode);            }        }        return keyEvent;    }
Many member variables are supported, and their names are easy to understand. Here I will briefly describe the two most commonly used ones:
  • MAction: Represents the keyevent action, which is the ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE defined in the system KeyEvent.
  • MKeyCode: Indicates which button you press, which is also defined in the system's KeyEvent. For example, 82 represents the key value of our system menu.
    public static final int KEYCODE_MENU            = 82;

3. since window event Inspector WindowManager needs to inject events to the system, the first thing to do is to first obtain the management class of the injection event, and then instantiate it to call it for us, the injection event uses the WindowManager class, and its instantiation starts initialization at monkey startup through the run called by the main function:
    private int run(String[] args) {        ...        if (!getSystemInterfaces()) {            return -3;        }        ....}
Then let's go to this method and see how the WindowManager we need is initialized.
    private boolean getSystemInterfaces() {        mAm = ActivityManagerNative.getDefault();        if (mAm == null) {            System.err.println("** Error: Unable to connect to activity manager; is the system "                    + "running?");            return false;        }        mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));        if (mWm == null) {            System.err.println("** Error: Unable to connect to window manager; is the system "                    + "running?");            return false;        }        mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));        if (mPm == null) {            System.err.println("** Error: Unable to connect to package manager; is the system "                    + "running?");            return false;        }        try {            mAm.setActivityController(new ActivityController());            mNetworkMonitor.register(mAm);        } catch (RemoteException e) {            System.err.println("** Failed talking with activity manager!");            return false;        }        return true;    }
Here we mainly want to understand some management classes used in it. Here, we are really worth noting about the WindowManager class, because when we inject real time, we actually call its method. Other classes are not used in our article, but now you can understand them by the way. Let's take a look at the ActivityManagerNative class information mentioned in the Code. For details, see the forwarded blog "ActivityManager framework Parsing". I personally think it is quite good. I will briefly describe the following according to my own understanding:
  • ActivityManager: Manages all the running activities of the system and obtains the running tasks, services, and memory information of the system. Normally, our application can be instantiated through (ActivityManager) getSystemService (Context. ACTIVITY_SERVICE. The operations provided by the method are implemented by the ActivityManagerNativeProxy proxy class.
  • ActivityManagerNative: ActivityManagerProxy implements the IActivitManager interface, but does not actually implement these methods. It is just a proxy class, and the execution of real actions is Stub ActivityManagerService. Only one ActivityManagerService object exists in the system_process process, activityManagerService inherits from the ActivityManagerNative stub class.
  • ActivityManagerProxy: The first line in the Code is mAm = ActivityManagerNative. getDefault (); The obtained object is actually the ActivityManagerProxy object, not ActivityManagerNative.
Next is the IWindowManager class. If you are not clear about it, please refer to the blog I forwarded earlier <windows, WindowManager, and Window management of Android>
  • IWindowManager: WindowManager is mainly used to manage the status, attributes, view addition, deletion, update, window order, message Collection and Processing of windows, but is hidden after android1.6. The reason why monkey can be called here is that it is compiled with the android source code. If there is no source code, the reflection mechanism should be used to obtain it by using Class. forName.

Then PackageManager:
  • PackageManager: This class of API is an encapsulation of all data structures based on loading information, including the following functions:
  • Install and uninstall an application to query permission information
  • Query Application-related information (application, activity, Cycler, service, provider, and related attributes)
  • Query installed applications
  • Add and delete permission
  • Clear user data, cache, code segments, etc.
The last part is SeriviceManager. For details, see ServiceManager and service management of Android.
  • ServiceManager: ServiceMananger is an important process in android. It is started after the init process is started. It can be seen from the name that it is used to manage the service in the system. For example, InputMethodService and ActivityManagerService. There are two important methods in ServiceManager: add_service and check_service. The system service needs to register its own information to ServiceManager through add_service. when it needs to be used, use check_service to check whether the service exists.

4. If WindowManager injects events into the system window, now we have obtained the WindowManager object. The next step is to see how MonkeyKeyEvent uses this object to send a key event to the System window. Locate the injectEvent method.
    @Override    public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) {        if (verbose > 1) {            String note;            if (mAction == KeyEvent.ACTION_UP) {                note = "ACTION_UP";            } else {                note = "ACTION_DOWN";            }            try {                System.out.println(":Sending Key (" + note + "): "                        + mKeyCode + "    // "                        + MonkeySourceRandom.getKeyName(mKeyCode));            } catch (ArrayIndexOutOfBoundsException e) {                System.out.println(":Sending Key (" + note + "): "                        + mKeyCode + "    // Unknown key event");            }        }        // inject key event        try {            if (!iwm.injectKeyEvent(getEvent(), false)) {                return MonkeyEvent.INJECT_FAIL;            }        } catch (RemoteException ex) {            return MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION;        }        return MonkeyEvent.INJECT_SUCCESS;    }
Note that input parameters
  • Iwm: This is the WindowManager instance object we obtained earlier.
  • Iam: ActivityManager instance object, which is not required here, but to be compatible with other MonkeyXXXEvent implementations of this interface method, it is still required to be passed in but not processed.
The entire method does not have much code, and finally the iwm is called. the injectKeyEvent method is used to input the system KeyEvent object created during MonkeyKeyEvent initialization to inject key events. This allows you to simulate Pressing System menus and other buttons.
5. monkey injection event processing method classification I used MonkeyKeyEvent as an instance to describe how to construct this type of event and how to call the injectKeyEvent method of the hidden class iWindowManager when rewriting MonkeyEvent to abstract the injectEvent of the parent class to inject button events. In fact, when the injectEvent method of MonkeyEvent is rewritten for other event types, it is not always true to inject events into the system window. For example, the injectEvent implemented by MonkeyThrottleEvent is actually just sleep:
    @Override    public int injectEvent(IWindowManager iwm, IActivityManager iam, int verbose) {        if (verbose > 1) {            System.out.println("Sleeping for " + mThrottle + " milliseconds");        }        try {            Thread.sleep(mThrottle);        } catch (InterruptedException e1) {            System.out.println("** Monkey interrupted in sleep.");            return MonkeyEvent.INJECT_FAIL;        }                return MonkeyEvent.INJECT_SUCCESS;    }
So although different MonkeyEvent implementation classes all implement the injectEvent method of the parent class, not all monkeyevents need to inject events. I think Google engineers are not good at the names of all this interface method. For example, handleEvent will not cause confusion (personal opinion). The following lists the different solutions for key events supported by monkey:

Event handling method

MonkeyEventImplementation class

Key code

Note

Inject events through WindowManager

MonkeyKeyEvent

InjectKeyiwm. injectKeyEvent (getEvent (), false) Event


MonkeyTouchEvent

Iwm. injectPointerEvent (me, false)


MonkeyTrackballEvent

Iwm. injectTrackballEvent (me, false)


By sending Command Injection events to the event device/dev/input/event0

MonkeyFlipEvent

FileOutputStream ("/dev/input/event0 ")


Use the startInstrumentation method of ActvityManager to start an application.

MonkeyInstrumentationEvent

Iam. startInstrumentation (cn, null, 0, args, null)


Sleep

MonkeyThrottleEvent

Thread. sleep (mThrottle)


MonkeyWaitEvent

Thread. sleep (mWaitTime)



6. The Command mode of MonkeyEvent indicates that MonkeyEvent is designed in the Command mode. How is the command design mode? Let's take a look.
Let's check whether the MonkeyEvent design meets the requirements of the command mode:
  • Command: MonkeyEvent, declares the injectEvent execute Interface Method
  • ConcreteCommand: MonkeyEvent implementation classes: MonkeyKeyEvent, MonkeyTouchEvent, MonkeyWaitEvent...
  • Client: Monkey. Remember that it calls mEventSource in the runMonkeyCyles method. the getNextEvent () method obtains the event from the event source and creates the corresponding event (ConcretCommand) based on the translateCommand method of each event source? If you do not remember, read the Monkey source code analysis running process and Monkey source code analysis event source.
  • Cycler: Instance objects such as WindowManager, because they finally implement and execute the injectXXXEvent requests.
  • Invoker: Monkey, because the direct call of the MonkeyKevent (command) injectEvent (execute) method is still in the Monkey runMonkeyCeles method: ev. injectEvent (mWm, mAm, mVerbose ). Therefore, Monkey plays both the hungry Command role and the Invoker role.
We can see that the MonkeyEvent design indeed satisfies the Command mode. What are the advantages of this design? If you don't know, you 'd better go to google by yourself. Here I am not proficient in design patterns, so I can only analyze the actual situation, check whether the advantages of this design model described on the Internet are obtained in our monkey:
  • (1) The command mode makes it easy to add new commands to the system: true! If a Command is added to handle off-screen events, we only need to add MonkeyBlowEvent class and implement the injectEvent interface, then, call the corresponding volume er in it to inject the Blow event.
  • (2) The party that is allowed to receive the request decides whether to reject the request: I have no idea what is the benefit.
  • (3) It is easier to design a command queue: indeed! Monkey is to abstract all events into monkeyevents and put them in our EventQueque.
  • (4) The request can be easily revoked and restored: it is not used here, because once an event is consumed, it cannot be undone. You can't say that you have clicked a button to regret it. The program will not execute it after clicking it. Wait for you to send an undo command. However, it should be nice if it is used in the undo function of document editing.
  • (5) When necessary, you can easily log commands: Yes, each ConcreteCommand class is independent, so it is very easy to record the command. It is because my MonkeyKeyEvent command will not always be your MonkeyTouchEvent command.

How can I download the full-site source code with the SQL injection vulnerability?

Typical injection scenarios:
And 1 = 1 and an error occurred while adding and 1 = 2.
If an injection vulnerability exists, you can use a tool (ah d or Ming Kido) to guess his table name and field.
Find the website background and log in with the username and password you guessed. Go to the background to see if asp Trojans can be uploaded or where they can be used (Haiyang top 2006 or 13th Trojan Horse ).
Use the packaging function in the webshell to package the website into. mdb, and download the package and unpackage it.
If you have some technical skills, you can try to obtain the server.
The specific injection method can be
Www.3800hk.com.

Prevent injection:
Generally, the injection vulnerability does not filter dangerous SQL query statements such as 'and or on the page.
.
Filter these query keywords in the source code. You can also include a common anti-injection program in conn. asp.

Haha, I 've hacked some websites and hope these will be useful to you...

If you trust me, you can add my QQ: 524629117
I will try to give you the permission for this website.

There are ready-made DLL files and the simplest source code injection is required.

BOOL EnableDebugPrivilege (BOOL bEnable)
{

BOOL fOK = FALSE;
HANDLE hToken;
If (OpenProcessToken (GetCurrentProcess (), TOKEN_ADJUST_PRIVILEGES, & hToken ))
{
TOKEN_PRIVILEGES tp;
Tp. PrivilegeCount = 1;
LookupPrivilegeValue (NULL, SE_DEBUG_NAME, & tp. Privileges [0]. Luid );//
Tp. Privileges [0]. Attributes = bEnable? SE_PRIVILEGE_ENABLED: 0;
AdjustTokenPrivileges (hToken, FALSE, & tp, sizeof (tp), NULL, NULL );
FOK = (GetLastError () = ERROR_SUCCESS );
CloseHandle (hToken );
}
Return fOK;
}
// Write Memory note: The commented out part cannot be used in this program, because the program can be accessed directly without permission issues
BOOL me_WriteProcessMemory (DWORD dwProcsPID, DWORD dwAddress, LPVOID Data, SIZE_T SIZE)
{
// EnableDebugPrivilege (true );
DWORD size;
HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, dwProcsPID); // PROCESS_VM_WRITE | PROCESS_VM_READ
// DWORD dwOldProc;
// DWORD dwNewProc;
// Change the page attribute to read/write
// VirtualProtectEx (hProcess, (LPVOID) dwAddress, SIZE, PAGE_READWRITE, & dwOldProc );

Bool re = WriteProcessMemory (hProcess, (LPVOID) dwAddress, Data, SIZE, & size );
// Restore the properties of the page file
// VirtualProtectEx (hProcess, (LPVOID) dwAddress, SIZE, dwOldProc, & dwNewProc );
CloseHandle (hProcess );

// EnableDebugPrivilege (false );
Return RE;
}
// READ memory
BOOL me_ReadProcessMemory (DWORD dwProcsPID, DWORD dwAddress, LPVOID Data, SIZE_T SIZE)
{
// EnableDebugPrivilege (true );
DWORD size;
HANDLE hProce ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.