In-depth mining of Windows Script Technology page 1/2

Source: Internet
Author: User

In-depth exploration of Windows Script Technology

ArticleAuthor: zzzevazzz <zzzevazzz@126.com>

To enableCodeClean and use the PHP tag of the forum for processing. (No vbs label, code label is not easy to use, depressing)
If you reprint this article, make adjustments accordingly.

[Directory]
1. Preface
2. Review wsh objects
3. WMI Service
4. The script also has a GUI
5. Anti-Virus
6. Create a backdoor.
7. Conclusion
8. References

[Preface]
This article describes some Windows Script Programming knowledge and skills. Here, Windows scripts refer to "Windows Script Host" (wsh Windows Script Host), rather than scripts in HTML or ASP. The former is explained by wscript or cscript, and the latter is explained by IE and IIS respectively. The description language is VBScript. This article assumes that the reader has a certain foundation for Windows Script Programming. If you do not know about this, please first learn Windows Script technology [1].

[Review wsh object]
Thanks to the support of COM technology, wsh can provide more powerful functions than batch processing (. BAT. To put it bluntly, wsh only calls the ready-made "control" as an object and uses the attributes and methods of the object to achieve its purpose.

Common objects include:
Wscript
The root object of the Windows Script Host object model cannot be left without wsh. It provides multiple sub-objects, such as wscript. Arguments and wscript. Shell. The former provides access to the entire command line parameter set, and the latter can runProgram, Manipulate the Registry content, create shortcuts, or access system folders.

Scripting. FileSystemObject
It is mainly designed for IIS to access the file system. This is probably the most common object, because almost all Windows Script Viruses need to copy and infect others.

ADODB. Stream
The sub-object of the ActiveX Data Objects database, which provides the ability to access files through a stream. This is part of the database, but thanks to Microsoft, ADO comes with the system.

Microsoft. XMLHTTP
Objects designed to support XML are accessed over HTTP. This vulnerability is often used for cross-site scripting and SQL injection.

There are many other uncommon ones:
Objects related to the Active Directory Service Interface (ADSI), which has a wide range of functions and is mainly used for Windows Domain Management.
Internetexplorer object-do all the things that IE can do.
Word, Excel, and outlook objects-used to process Word documents, Excel forms, and emails.
WBEM object -- WBEM is Web-Based Enterprise Management. It provides powerful functions for Windows Management. The WMI Service mentioned in the next section provides interfaces for this object.

Obviously, wsh can exploit more objects than that. This article describes some useful objects and their usage.
First, let's look at an example that supports resumable download of web resources. It uses the four common objects mentioned above.Copy codeThe Code is as follows: if (lcase (right (wscript. fullname, 11) = "wscript.exe") Then 'determine The Script Host name'
Die ("Script Host must be cscript.exe.") 'The Script Host is not a cscript, so die'
End if

If wscript. Arguments. Count <1 then ', there must be at least one parameter'
Die ("Usage: cscript webdl. vbs URL [filename]") 'Although Sparrow is small and dirty, usage cannot be forgotten'
End if

Url = wscript. Arguments (0) 'parameter array subscript starts from 0'
If url = "" Then die ("URL can't be null.") 'dare to tell me, empty URL may not work'
If wscript. Arguments. Count> 1 then ', first judge whether the number of parameters is greater than 1'
Filename = wscript. Arguments (1) 'Access the second parameter'
Else 'get from URL if no file name is given'
T = faster Rev (URL, "/") 'Get the last "/" location'
If T = 0 or T = Len (URL) Then die ("can not get filename to save.") 'No "/" or end'
Filename = right (URL, Len (URL)-T) 'get the file name to be saved'
End if
If not left (URL, 7) = "http: //" then url = "http: //" & url ", if you forget" http: // "carelessly, add'

Set FSO = wscript. Createobject ("scripting. FileSystemObject") 'fso, Aso, and HTTP. Each object must be unique'
Set Aso = wscript. Createobject ("ADODB. Stream ")
Set HTTP = wscript. Createobject ("Microsoft. XMLHTTP ")

If FSO. fileexists (filename) Then 'determine whether the object to be downloaded already exists'
Start = FSO. GetFile (filename). Size 'exists, with the current file size as the starting position'
Else
Start = 0 'nonexistent, everything starts from scratch'
FSO. createtextfile (filename). Close 'create file'
End if

Wscript. stdout. Write "connectting..." 'the beginning of the play'
Current = start 'current position is the start position'
Do
HTTP. Open "get", URL, true 'HTTP is called asynchronously here'
HTTP. setRequestHeader "range", "bytes =" & start & "-" & CSTR (start + 20480) 'here is the secret of resumable upload'
HTTP. setRequestHeader "Content-Type:", "application/octet-stream"
HTTP. Send' start sending after data packets are constructed'

For I = 1 to 120 'cyclic waiting'
If HTTP. readystate = 3 then showplan () 'status 3 indicates that the data is received and the progress is displayed'
If HTTP. readystate = 4 then exit for 'status 4 indicates the data is accepted successfully'
Wscript. Sleep 500 'Wait for 500ms'
Next
If not HTTP. readystate = 4 then die ("timeout.") '20 k hasn't been finished in 1 minute? Timeout! '
If HTTP. Status> 299 then die ("error:" & HTTP. Status & "& HTTP. statustext) 'Isn't it, and an error occurs? '
If not HTTP. Status = 206 then die ("server not support partial content.") 'the server does not support resumable upload'

Aso. type = 1 'data stream type set to byte'
Aso. Open
Aso. loadfromfile filename 'open file'
Aso. Position = start 'set the initial position of the file pointer'
Aso. Write HTTP. responsebody 'write Data'
Aso. savetofile filename, 2 'overwrite'
Aso. Close

Range = http. getResponseHeader ("content-range") 'Get "content-range"' in the HTTP Header "'
If range = "" Then die ("can not get range.") 'You don't know if the download is complete'
Temp = mid (range, instr (range, "-") + 1) 'content-range is similar to 123-456/789'
Current = clng (left (temp, instr (temp, "/")-1) '2014 is the start position and 123 is the end position'
Total = clng (mid (temp, instr (temp, "/") + 1) '100 is the total number of bytes of the file'
If total-current = 1 then exit do 'the end position is 1 less than the total size, indicating that the transfer is completed'
Start = start + 20480 'otherwise download 20 k'
Loop while true

Wscript. Echo CHR (13) & "download (" & total & ") Done." 'after downloading, the total number of bytes is displayed'

Function die (MSG) 'function name comes from Perl built-in function die'
Wscript. Echo MSG 'last words ^_^'
Wscript. Quit 'Go to see Marx'
End Function

Function showplan () 'display download progress'
If I mod 3 = 0 then c = "/" 'simple dynamic Effect'
If I mod 3 = 1 then c = "-"
If I mod 3 = 2 then c = "\"
Wscript. stdout. write CHR (13) & "download (" ¤ T & ")" & C & CHR (8) '13. the ASCII code is returned to the beginning of the line, and 8 is returned to the geolde'
End Function

As you can see, the HTTP control is very powerful. Through operations on the HTTP header, it is easy to implement resumable data transfer. In this example, it is only a single thread. In fact, because the HTTP control supports asynchronous calls and events, multi-thread download can also be implemented. Detailed usage is provided in msdn. For more information about resumable data transfer, see rfc2616.

What is the difference between FSO and ASO that they can access files? In fact, in addition to accessing byte (non-text) data, Aso is unnecessary. If you want to implement ASO in the example using FSO, an error will occur when writing HTTP. responsebody. Otherwise, Aso cannot determine whether the file exists. If the file does not exist, loadfromfile will cause a direct error and there is no chance of correction. Of course, you can use the on error resume next statement to let the Script Host ignore non-fatal errors and capture and process them by yourself. But why is there a ready-made fileexists?

In addition, because FSO is often used by script viruses and ASP Trojans, the Administrator may modify the control information in the registry so that the script cannot be created. In fact, execute a command regsvr32/s scrrun. dll and it will be restored. Even if scrrun. dll is deleted, just copy it.

After the warm-up, let's take a look at a powerful object-WBEM (provided by Wmi ).

[WMI Service]
First, let's take a look at how WMI is described in msdn-Windows Management specifications (Wmi) are scalable system management structures that use a unified, standard-based, and scalable object-oriented interface. When I first understood WMI, I thought that WMI was a "Windows Management Interface.

Let's look at what a WMI Service is. It provides a common interface and object mode to access management information about operating systems, devices, applications, and services. If this service is terminated, most Windows-based software will not work properly. If this service is disabled, any service dependent on it cannot be started.

It seems to be a very important service. However, by default, the Service does not depend on it. Instead, it depends on the RPC and EventLog services. But it is often used. I set the WMI Service to start and stop manually. After using the computer for a while, I found that the WMI Service was started again. Start the service as needed. This is a feature that sets the service to "Manual. When I know how large the management information provided by WMI is, I am not surprised at the self-launch of the WMI Service.

You can use the tool wmitools.exe [2] to directly understand wmicontent. This is a tool set. Using the WMI Object Browser, you can see that many objects provided by WMI are no less complex than the registry. More importantly, WMI also provides dynamic information, such as the current process, service, and user.

The logical structure of WMI is as follows:
First, WMI users, such as scripts (specifically the Script Host) and other applications that use the WMI interface. WMI users access the CIM Object Manager Winmgmt (WMI Service), which then accesses the CIM (Common Information Model) repository. Static or dynamic information (Object Attributes) is stored in the CIM library, and object methods are also stored. Some operations, such as starting a service, are implemented by executing objects. This actually calls various DLL through COM technology. Finally, the request is completed by the API encapsulated in the DLL.

WMI is event-driven. The operating system, service, application, and device driver can be used as event sources to generate Event Notifications Through the COM interface. Winmgmt captures the event and refresh the dynamic information in the CIM library. This is why the WMI Service depends on EventLog.

After talking about the concept, let's take a look at how to operate the WMI interface.
The Code in the following example is from the script RTCs I wrote. It is a script for remotely configuring the telnet service.
Here only the key parts are listed:

first, create an object and connect to the server: copy Code the code is as follows: Set objlocator = Createobject (" wbemscripting. swbemlocator ")
set objswbemservices = objlocator. connectserver (IPaddress, "Root \ default", username, password)

first, create a service locating object, and then use the connectserver method of the object to connect to the server.
in addition to the IP address, user name, and password, there is also a namespace parameter Root \ default.
just as the Registry has a root key, the CIM library is also classified. It is described in Object-Oriented terms as "Name Space ).
to handle NTLM authentication and telnet port, you need to access the registry. The object for operating the registry is Root \ default. copy Code the code is as follows: set objinstance = objswbemservices. get ("stdregprov") 'instantiate stdregprov object'
set objmethod = objinstance. methods _ ("setdwordvalue") 'setdwordvalue method itself is also an object '
set objinparam = objmethod. inparameters. spawninstance _ () 'instantiate input parameter object'
objinparam. hdefkey = & h80000002 'the root directory is HKLM, code 80000002 (hexadecimal) '
objinparam. ssubkeyname = "SOFTWARE \ Microsoft \ telnetserver.0" 'set subkey'
objinparam. svaluename = "NTLM" 'set the key value name'
objinparam. uvalue = NTLM 'sets the key value content. NTLM is a variable, determined by the user input parameter'
set objoutparam1_objinstance.exe cmethod _ ("setdwordvalue", objinparam) 'execution method'

Then set the portCopy codeThe Code is as follows: objinparam. svaluename = "telnetport"
Objinparam. uvalue = port 'port is also a parameter input by the user'
Set objoutparam1_objinstance.exe cmethod _ ("setdwordvalue", objinparam)

Do you think this is too big? It is also the namespace and class instantiation. When I first started studying WMI, I felt very uncomfortable. I remember my junior high school teacher said that reading books should be thick before reading books. The reason for reading is that you have added your own ideas, and the reason for reading thin books is to grasp the essentials.
Now we will read the book thin. The above code can be changed:Copy codeThe Code is as follows: Set olct = Createobject ("wbemscripting. swbemlocator ")
Set oreg = olct. connectserver (IP, "Root \ default", user, pass). Get ("stdregprov ")
HKLM = & h80000002
Out = oreg. setdwordvalue (HKLM, "SOFTWARE \ Microsoft \ telnetserver.0", "NTLM", NTLM)
Out = oreg. setdwordvalue (HKLM, "SOFTWARE \ Microsoft \ telnetserver.0", "telnetport", Port)

Is it much easier now?

The next step is to control the telnet service status.Copy codeThe Code is as follows: Set objswbemservices = objlocator. connectserver (IPaddress, "Root \ cimv2", username, password)
Set colinstances=objswbemservices.exe cquery ("select * From win32_service where name = 'tlntsvr '")

This connection uses the Root \ cimv2 namespace. Then, use WQL (SQL for WMI) to search for the TlntSvr Service. If you are familiar with SQL syntax, you will know what you are doing. In this case, a group of win32_service instances are obtained, although the where statement determines that the group always has only one member.
For simplicity, assume that you only need to switch the service status.Copy codeThe Code is as follows: for each objinstance in colinstances
If objinstance. Started = true then 'determine whether the service has been started based on started attributes'
Intstatus = objinstance. stopservice () 'Yes, call stopservice to stop the service'
Else
Intstatus = objinstance. startservice () 'No, call startservice to start Service'
End if
Next

This is the key code, and the rest are code that handles input and output and fault tolerance.
Summary process:
1. Connect the server and the appropriate namespace.
2. Use the get or execquery method to obtain one or more instances of the desired object.
3. Read and Write object attributes, and call object methods.

So, how do I know which namespace to connect and what objects to obtain? WMI Technical Guide [3] lists a large number of common objects. Unfortunately, it does not have a corresponding e-book. You only need to find it in the bookstore. You can also use the wmi cim studio tool in wmitools to search for desired objects. After finding the object, wmi cim studio can list its attributes and methods, and then go to msdn to find specific help. For example, in addition to the seven RS series scripts I wrote, the application also provides reference materials [4].

Note that in reference [4], the following syntax is used to connect to the server and namespace:
Codz:
Set ob1_miservice = GetObject ("winmgmts :! \ "& Strcomputer &" \ Root \ cimv2: win32_process ")

The detailed syntax is described in the WMI Technical Guide and msdn, but we don't care about it because there is no user name or password parameter in this method. Therefore, this function can be used only when the current user has the logon permission on the target system (including local hosts. To use connectserver locally, the first parameter can be 127.0.0.1 or a ".". 3rd or four parameters are empty strings "".

Finally, access to WMI has a "Privilege" problem. If you have read the rots code, you will find two "strange" statements:
Codz:
Objswbemservices. Security _. Privileges. Add 23, true
Objswbemservices. Security _. Privileges. Add 18, true

This is to apply for permissions from the WMI Service. Both 18 and 23 are permission codes. Some important codes are listed below:
5. Create an account in the domain
7. manage audit, view, save, and clear security logs
9. Load and uninstall the device driver
10 record system time
11. Change System Time
18 local Shutdown
22. bypass the calendar check
23 remote shutdown allowed

For more information, see WMI technical guide or msdn.
All privileges are not available by default. When I was writing RCAs, I forgot to apply for privilege 11 and the test failed for a long time.
As long as you have the permission to connect to the WMI Service, you can successfully apply for the required privilege. This kind of privileged mechanism only aims to constrain the behavior of applications and enhance system stability. It is strange that you do not have to apply for any privileges to access the registry. I really don't know what Microsoft developers think, maybe it's too common to access the registry.

[The script also has a GUI]
Although the system provides two script hosts: wscript and cscript, which are responsible for running scripts in the window environment and command line environment, in fact, it is not convenient for users to interact with scripts in the window environment: you can only create a shortcut for parameter input or the inputbox dialog box is displayed. The output information can continue to run only after the user "OK. The Window environment is no longer intuitive and quick. Fortunately, there is an internetexplorer object mentioned above. The script can provide a web-style GUI.

let's take a look at the example. For a script to clear system logs, review WMI: copy Code the code is as follows: Set Ie = wscript. createobject ("internetexplorer. application "," Event _ ") 'create ie object'
IE. menubar = 0 'cancel menu bar '
IE. addressbar = 0 'cancel the address bar'
IE. toolbar = 0 'cancel toolbar '
IE. statusbar = 0 'cancel the status'
IE. width = 400 'width 400 '
IE. height = 400 'height 400 '
IE. resizable = 0 'do not allow users to change the window size'
IE. navigate "about" & ": blank" 'Open the blank page'
ie.left?fix(ie.doc ument. parentwindow. screen. availwidth-ie.width)/2) 'horizontally centered '
ie.top;fix(ie.doc ument. parentwindow. screen. availheight-ie.height)/2) 'vertical Center'
IE. visible = 1' window visibility '

with ie.doc ument 'call document below. write method, '
. write " " 'write an HTML section to the IE window. '
. write "

remote clearing of system logs


"
. write "

Target IP address: " 'You can also use the navigate method to directly open a'
. write "

User name: " 'HTML files, the effect is the same. '
. write "

password: "
. write "

type:" 'not only indicates the input object, but also all DHTML support'
. write " application" 'objects, attributes, and methods can be used. '
. write " System"
. write " Security" 'Methods for accessing these objects and webpage access'
. write "


" 'objects in the framework are similar. '
. write ""
. write ""
. write " "
end with

Dim WMI 'explicitly defines a global variable'
Set wnd=ie.doc ument. parentwindow 'set WND as the window Object'
Set id=ie.doc ument. All 'Set ID to the set of all objects in document'
Id. Confirm. onclick = getref ("Confirm") 'sets the processing function when you click "OK'
Id. Cancel. onclick = getref ("cancel") 'sets the processing function when the "cancel" button is clicked'

Do While true 'because the IE Object supports events, the corresponding ,'
The wscript. Sleep 200 'script waits for events in an infinite loop. '
Loop

Sub event_onquit 'ie exit event processing Process'
Wscript. Quit 'when ie exits, the script also exits'
End sub

Sub cancel '"cancel" event processing Process'
Ie. Quit 'Call the quit method of IE and close the IE Windows'
End sub 'will then trigger event_onquit, so the script also exits'

sub confirm '"OK" indicates the event processing process, which is the key'
with ID
If. IP. value = "" then. IP. value = ". "'null IP value indicates local operation by default '
if not (. app. checked or. SYS. checked or. sec. checked) then'app and so on are all checkboxes. By detecting their checked'
WND. alert ("select at least one log") 'attribute to determine whether the log is selected. '
exit sub
end if
set LCT = Createobject ("wbemscripting. swbemlocator ") 'create server locating object'
on error resume next' causes the Script Host to ignore non-fatal error'
set WMI = LCT. connectserver (. IP. value, "root/cimv2 ",. user. value ,. pass. value) 'connect to the root/cimv2 namespace '
If err. number then 'capture and handle the error'
WND. alert ("failed to connect to WMI server") 'here is a simple display of "failed"'
err. clear
on error goto 0' still allows the Script Host to handle all errors '
exit sub
end if
If. app. checked then clearlog "application" 'clear each selected log'
If. SYS. checked then clearlog "system"
If. sec. checked then clearlog "security" 'Note that security logs cannot be cleared due to restrictions in XP'
WND. alert ("logs cleared")
end with
end sub

Sub clearlog (name)
WQL = "select * From win32_nteventlogfile where logfilename = '" & name &"'"
Set logslogs wmi.exe cquery (WQL) 'note that logs members are not each log ,'
For each L in logs, but specifies the log file object. '
If l. cleareventlog () then
An error occurred while WND. Alert ("clearing logs" & name! ")
Ie. Quit
Wscript. Quit
End if
Next
End sub

Summarize the entire process. First, create the internetexplorer. Application object. The direct effect is to start an iexplorer process, but the window is invisible until IE. Visible = 1 is set. Then, use the document. Write method to write the HTML statement to the IE window. For complex interfaces, you can save the HTML code as an HTML file and open it with IE. navigate (filename. Finally, the input in the response window. This is basically a Knowledge Area of DHTML.

The biggest difference from General scripting is that IE is event-driven. All you need to do is set the corresponding event processing function/process.
In this example, the script only cares about three events: IE exits, the "OK" button is clicked, and the "cancel" button is clicked.

Note: In this example, there are only two statements for setting the event processing process, and no association is defined between the IE exit event and the event_onquit process. This is because the second parameter "Event _" when an IE Object is created is a prefix. The event processing process name of the IE Object is the prefix and the event name. Therefore, the onquit event processing process is event_onquit by default.

After you click "OK", the confirm process is called. In this example, the object in another example, such as ie.doc ument. All. IP. value, is input in the "target IP" text box. If the "application" checkbox is selected, the value of ie.doc ument. All. App. Checked is true; otherwise, the value is false. Use ie.doc ument. parentwindow. alert if you want to call alertsung. The access methods for other IE objects are similar. For more information, see DHTML.

With the web interface, interaction becomes rich and colorful. You can make full use of your creativity.

For example, many GUI tools (such as streamer) have a logo page to display copyright and other information at startup. We can use the IE Object to simulate one:Copy codeThe Code is as follows: Set Ie = wscript. Createobject ("internetexplorer. application ")
Ie. fullscreen = 1
Ie. width = 300
Internet Explorer. Height = 150
Ie. navigate "about" & ": blank"
Ie.left1_fix(ie.doc ument. parentwindow. Screen. availwidth-ie.width)/2)
Ie.topdeskfix(ie.doc ument. parentwindow. Screen. availheight-ie.height)/2)
Ie.doc ument. Write "<body bgcolor = skyblue scroll = NO> <br> "&_
"<H2 align = center> This is a logo </H2> </body>"
Ie. Visible = 1
Wscript. Sleep 5000
Ie. Quit

After the above code is executed, an IE window without a title bar or border is displayed in the center of the screen, lasting 5 seconds.
In the window, there is a blue-colored black text "this is a logo ".

After the script is Gui-based, the interaction with the user is more intuitive. There are a lot of parameter tools like NMAP. When using them locally, it is enough to write an interface for the graphic interface. The output results can also be displayed in a script that is more suitable for reading, just like the HTML scan report generated by tools such as streamer.

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.