Development Principle and Implementation of Windows Task Manager

Source: Internet
Author: User
The task manager (taskmgr) in Windows 2000/XP is familiar to everyone. In contrast, the task manager in XP is more powerful than, and the returned information is more detailed, but do you think there are still a lot of messages you want to get that are not included in it? Do you think the windows system management toolbox is too scattered? Next let's take a look at their development principles and implement a real task manager. Now we call WIN32API to implement these functions, but we all say that Ms hides too many details. We will discuss more about Windows kernel in the future.

You may be familiar with the task manager to manage several processes. When we suspect a virus or Trojan, we will check whether there are any special processes running in the task manager, so process viewer should be a very important feature. In addition to the process name, what else do we need? Including its process identifier (processid), user information (username), CPU usage time (cputime), memory usage (memoryusage), and its priority (basepriority ).

CPU and memory information can help us analyze the running status of the process, and priority can indicate the priority of the process when the CPU is allocated to the CPU for use. These are common process information. Let's look at other information. Parent process ID, create time ),ProgramIn many cases, such names are also the information we care about. Let's look at the process-related performance information. In Windows, there are usually two modes: Kernel Mode (kernel: Level 0) and user mode (User: Level 3). The process usually switches back and forth between the two modes, therefore, you can obtain the time each process uses in kernel mode and user mode. It also includes workingset, pagedpool, nonepagedpool, and pagefile information related to processes. Process-related I/O operations include read, write, and other actions. We can obtain the number of these operations and the number of data transferred.

If you suspect that a process is a Trojan, what information do you want to obtain? Simple process names are not enough! We hope to obtain the path of the actual program of the process, which can help us determine whether the program is running. Some time ago, we were not discussing what process is hidden. One of them was "creating remote Threads", and the injection body often existed in the form of dynamic link library (DLL, we want to see all the modules contained in a specific process, often DLL. "Thread" is a familiar name. It is the implementation body in windows, while the process is the environment where the thread runs. How many threads have a process created? We can also enumerate information about all threads in a process. If you find a Trojan process, the following actions should be to analyze its running mechanism (if you are interested in it), but you should end it eventually. In windows2k, many key processes in the system cannot be terminated in taskmgr, but now you don't have to worry about it. Okay. operations on the process include, of course, killing the process. If you have used XP in Chinese, do you often encounter "false dead" in the taskbar? Even though your computer has not crashed, it cannot be moved, well, we can also hook up any process. No matter what action you do to it (except the end), it will not respond. With the process suspended, we can also activate the process from the "suspended" status.

Desktop windows are the most frequently accessed interactive interfaces. Do you want to obtain the title information of each window? Of course, we can also obtain the process, thread, and window handle attributes associated with the window. If you are familiar with VC, You should know one of the spy ++ tools to obtain detailed information about desktop windows, processes, and threads, but you do not need to open this tool now, open that. It's done! System performance is a concern of every user. (Friendly reminder: There are a lot of tips in the developer's Web windows development column) It includes the number of handles, processes, and threads currently created by the entire system. There are also the total amount and usage of physical memory (physical memory), the size of the system cache, the memory retention and submission (commit charge) status, of course, there is also the use of the core paging/non-Paging pool (kernel memory. It covers almost most of the information about memory management in windows.

Although the hard disk price is already very low, I am still using the 6.4g small, so often encounter "low disk "! We often need to check the usage of the hard disk, but it is too troublesome to access my computer every time. Now we can understand the capacity and current usage of all disks at a time, as well as their format types (such as fat, NTFS, CDFs, etc.) and disk tags.

When it comes to environment blocks, it may not be so familiar. It contains some environment variables, and each environment variable corresponds to one or more strings, you can set them in system/advanced of the control panel, including adding new environment variables, deleting and editing system environment variables.

Event Recording is of great help to analyze the usage of the system. There are three types of event records: application, system, and security. Each event can be divided into several types, including common information, warnings, and errors. Including record number, event type, identifier, source, time generated, and user) and description ). When you have time, you can look at the event information. Of course, every network administrator should be familiar with it, but it also includes other event log information.

I often use the ipconfig/all command in windows, because we use DHCP. It's okay to see if your IP address has changed. It includes detailed information about the network adapter, including the adapter name, description, hardware address and type, IP address and corresponding subnet mask, Gateway and DHCP server address. (Friendly reminder: There are still a lot of tips in the developer's Web windows development column) but are you interested in network traffic? Of course, we can obtain the number (not) of broadcast datagram received/sent by the host, the number of errors, and the total number of received/sent messages, which is useful to every netizen.

Network Sharing is often a matter of attention. What information are you sharing, what file paths are, and their sharing type information. When we do not need some shared information, we should not forget to delete it to avoid leaking our confidential information.

Windows NT is a multi-user system that allows the presence of multiple types of users. We want to obtain the user account's validity period (password expired), remember to modify the user's password at any time, as well as the user ID, group ID ), there is also the type of the user account. Different types have different permissions. We certainly hope to have the highest power! Check whether the system has limits on the disk space usage of an account (max storage), number of logon and logon time (logon hours, it is also helpful for us to analyze user usage.

The system's Win32 service and device driver information are also very important. We hope to detect the specific path, status, type, startup mode, and other information of each service/device startup program. We also want to control services, such as stopping, starting, and deleting services. For more information about the Win32 service, see "Analysis of Windows2000/XP services and backdoors.

Shutdown is not so monotonous. You can log out of your system. If you want to leave, you need to lock it. Recently, everyone does not like shutdown, which is too troublesome, so they are used to hibernation. The system will keep the current information for us, but there are also shutdown and sleep support for power management. Windows users have noticed that we can also use the shutdown and restart functions with the arrival notes and message prompts In the XP system.

The version information of the system is relatively fixed, including operating system fingerprints, registered organizations/users, host names and system-related directories.

After talking about this, we should also talk about how to implement it.

1. Window Information

Ms provides functions for opening a specific desktop and enumerating a desktop window.

Hdesk = opendesktop (lpszdesktop, 0, false, reply top_enumerate );
// Open our default desktop;
Enumdesktopwindows (hdesk, (wndenumproc) enumwindowproc, 0 );
// Enumeration opens all windows on the desktop and is implemented by the callback function.
Bool _ stdcall enumwindowproc (hwnd, lparam );
// In the callback function, we can obtain the title of the window, related processes, and thread information;
Getwindowtext (hwnd, szwindowtext, dwmaxcount );
Getwindowthreadprocessid (hwnd, & dwpid );

2. device drive information (the service is similar to the device drive and is not repeated here)

The device driver information is managed by the Service Control Manager (SCM). I want to open the Service Control Manager and enumerate all the device drivers.

Openscmanager (null, null, SC _manager_all_access );
// Open the Service Control Manager with all permissions;
Enumservicesstatus (schmanager, dwdevicetype, dwdevicestate,
Enumstatus, dwbufsize, & dwbytesneeded,
& Dwdevicesreturned, & dwresumehandle ))
// Enumerate the current status of all devices;
Closeservicehandle (schmanager );
// Remember to close the Service handle after the access is completed;
Openservice (schmanager, szdevicename, service_all_access );
// Open the drive of the specified device;
Queryserviceconfig (schdevice, lpdeviceconfig,
1024*8, & dwbytesneeded );
// Query the service configuration information of the drive;
Queryservicestatus (schdevice, & devicestatus );
// Query the current status of the device drive. (Friendly reminder: There are a lot of skills in the developer's windows development column)
Queryserviceconfig2 (schdevice, service_config_description,
(Lpbyte) lpdevicedescription, 8*1024, & dwbytesneeded)
// Query the device description;
Startservice (schdevice, 0, null );
// Start the device;
Controlservice (schdevice, service_control_stop, & devicestatus );
// Stop the device;
Deleteservice (schdevice );
// Delete a device;

3. Disk Information

We hope to obtain information about all the disks in the system, including floppy disks, hard disks, and optical disks;

Getlogicaldrivestrings (dwbufferlength, lpbuffer );
// Obtain the information of the logical device;
Getvolumeinformation (lprootpathname, lpvolumenamebuffer,
Dwvolumenamesize, & dwvolumeserialnumber,
& Dwmaximumcomponentlength, & dwfilesystemflags,
Lpfilesystemnamebuffer, dwfilesystemnamesize );
// Obtain the disk volume information, including the volume name and format type. (Friendly reminder: There are a lot of skills in the developer's windows development column)
Getdiskfreespaceex (lprootpathname, & freebytesavailable,
& Totalnumberofbytes, & totalnumberoffreebytes );
// Test disk space usage;

4. Environment Variables

We can obtain the environment block information from the Registry: HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ environment. Of course, we must use the registry function.

Regopenkeyex (HKEY_LOCAL_MACHINE, regkey, 0, key_query_value, & hkey );
// Open the registry key;
Regenumvalue (hkey, dwindex, environvariable,
& Dwvariablelength, null );
// Query the required information values;
Getenvironmentvariable (environvariable, environstring, 1024 );
// Obtain the string information of the environment variable;

5. event record information

Openeventlog (null, szlog );
// Enable the time log record;
Getoldesteventlogrecord (hevent, & dwthisrecord );
// Obtain the latest log information to continue searching;
Readeventlog (hevent, eventlog_forwards_read │ eventlog_sequential_read,
0, peventlogrecord, 1024*32, & dwread, & dwneeded)
// Read the log information;
Lookupaccountsid (null, psid, szname, & dwname, szdomain, & dwdomain, & snu );
// Obtain the account Sid to obtain the account user name;
Getnumberofeventlogrecords (hevent, & dwtotal );
// Obtain the total number of Event Logs;
Closeeventlog (hevent );
// Do not forget to close the event handle;

6. Network Sharing

We use the second-level Internet shared search;

NetShareEnum (null, dwlevel, (pbyte *) & pbuf, max_preferred_length, & entriesread, & totalentries, & resume );
// List all shared directories and related information;
Netapibufferfree (pbuf );
// Release the buffer; (Friendly reminder: There are a lot of skills in the developer's windows development column)
Netincludel (null, (char *) lpsharenamew, 0 );
// Delete the shared network directory;

7. network adapter Information

We need to detect Nic information and network traffic;

Getadaptersinfo (& adapterinfo, & outbuflen );
// Obtain the adapter information;

8. System Performance

Obtain the memory usage of the system;

Getperformanceinfo (& perfinfo, sizeof (effecmace_information ))
// Obtain system performance information;

9. Process/thread/module information

Here we use tool help functions (toolhelp32) and systems

Openprocesstoken (getcurrentprocess (), token_query │ token_adjust_privileges, & htoken );
// Open the process token to raise the permission;
Adjusttokenprivileges (htoken, false, & tokenprivileges, sizeof (token_privileges), null, null );
// Escalate process permissions to support debugging (Debug );
Createconlhelp32snapshot (th32cs_snapprocess, 0 );
// Create a process snapshot;
Process32first (hprocesssnap, & processentry32 );
Process32first (hprocesssnap, & processentry32 );
// Enumerate all processes;
OpenProcess (process_query_information, false, processentry32.th32processid );
// Open a specific process to query process-related information;
Getprocesstimes (hprocess, & createtime, & exittime, & kerneltime, & usertime );
// Obtain the time information of the process;
Getprocessmemoryinfo (hprocess, & pmcounter, sizeof (pmcounter ));
// Obtain the stored area information of a process;
Getpriorityclass (hprocess );
// Obtain the priority of a process;
Getprocessiocounters (hprocess, & iocounters );
// Obtain the IO usage of the process;
Createconlhelp32snapshot (th32cs_snapmodule, dwprocessid );
// Create a module snapshot. (Friendly reminder: There are a lot of skills in the developer's windows development column)
Module32first (hmodulesnap, & moduleentry32 );
Module32next (hmodulesnap, & moduleentry32 );
// Enumerate process module information;
Createconlhelp32snapshot (th32cs_snapthread, 0 );
// Create a thread snapshot;
Thread32first (hthreadsnap, & threadentry32 );
Thread32next (hthreadsnap, & threadentry32 );
// Enumerate thread information;
Openthread (thread_all_access, false, threadentry32.th32threadid );
// Open the thread and obtain the function address by yourself;
Terminateprocess (hprocess, 0 );
// Terminate the process;
Suspendthread (hthread );
// Suspension thread;
Resumethread (hthread );
// Activate the thread;

10. Shutdown

Adjusttokenprivileges (htoken, false, & tokenprivileges, sizeof (token_privileges), null, null );
// Adjust the process token to enable shutdown;
Exitwindowsex (ewx_logoff, 0 );
// Log out of the system;
Lockworkstation ();
// Lock the system;
Initiatesystemshutdown (null, szmessage, dwtimeout, false, bsig );
// Supports shutdown/restart when the message is recorded and displayed;
Setsystempowerstate (bsig, false );
// System sleep/hibernation;

11. User Information

Netuserenum (null, dwlevel, filter_normal_account, (lpbyte *) & pbuf,
Dwprefmaxlen, & dwentriesread, & dwtotalentries, & dwresumehandle );
// Enumerate system user information;
Netuserdel (null, lpusernamew );
// Delete a specified user;

12. System Version Information

Getversionex (lposversioninfo) & osviex );
// Obtain the version information of the operating system;
You can also obtain related information through the registry (HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion:
Gettickcount ();
// Obtain the start time;
Getcomputername (szinfo, & dwinfo );
// Obtain the computer name;
GetUserName (szinfo, & dwinfo );
// Obtain the computer user name;
Getwindowsdirectory (szinfo, max_path + 1 );
// Obtain the Windows directory;
Getsystemdirectory (szinfo, max_path + 1 );
// Obtain the system directory;

Summary:

Although we have now implemented various functions of the task manager, even more powerful than the built-in functions of windows, there is no excitement. Because look at ourCode, You will find that all those are directly called WIN32API functions, but do we know how the underlying system is implemented? Whether we want to implement a function or be interested in the operating system, we should do more research on the underlying system, not just programmers who only use high-level functions. Although Microsoft hides a lot of internal details for us, it is precisely this underlying secret that inspires our interest and motivation for in-depth research on it.

Related Article

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.